Course: JavaScript

Progress (0%)

  1. Foundation

  2. Numbers

  3. Strings

  4. Conditions

  5. Loops

  6. Arrays

  7. Functions

  8. Objects

  9. Exceptions

  10. HTML DOM

  11. CSSOM

  12. Events

  13. Drag and Drop

  14. opt Touch Events

  15. Misc

  16. Project: Analog Clock

Exercise: Div Clicked?

Exercise 54 Easy

Prerequisites for the exercise

  1. JavaScript Events — Event Objects
  2. JavaScript Events — Basics
  3. All previous chapters

Objective

Given an HTML document, determine if a click occurred anywhere inside a <div> element.

Description

Consider the following HTML document:

<h1>"Div Clicked?" Exercise</h1>

<div>Div 1</div>

<p>This is a paragraph.</p>

<div>
   Div 2
   <button>A button</button>
</div>

<p>This is another paragraph.</p>

<div>
   Div 3
   <h2>A sub-heading</h2>
   <p>This is yet another paragraph with a <span>span inside it</span>.</p>
</div>

along with the generic styles shown below:

div {
   background: #eee;
}

The result could be seen as follows:

Live Example

Now in this exercise, you have to set up a click handler on window to determine if a click occurs anywhere on this document from within a <div> element.

If this is the case, the program must alert the text "Div clicked!". Otherwise, it should do nothing.

For instance, the click could be made on the <span> element, which is nested inside a <p> element, which is nested inside a <div> element. Consequently, the alert must be shown in this case.

View Solution

New file

Inside the directory you created for this course on JavaScript, create a new folder called Exercise-54-Div-Clicked? and put the .html solution files for this exercise within it.

Solution

The solution to this exercise is dead simple. Seriously!

First we ought to set up a click handler on window. We could do so using the onclick property or even the addEventListener() method. For brevity, we'll go with the former.

window.onclick = function(e) {
   // Code to go here.
}

Next, we have to start iterating from e.target and go all the way document, traversing up each element's parent node, in search of an element that's a <div>.

But how to check a <div>?

Well it's pretty straightforward: inspect the nodeName attribute of the element node and compare it with 'DIV'.

This is accomplished below:

window.onclick = function(e) {
   var element = e.target;
   while (element !== document) {
      if (element.nodeName === 'DIV') {
         // Div found!
      }
      element = element.parentNode;
   }
}

Finally, as instructed in the exercise's description, if a <div> is found, we must alert the text "Div clicked!". We accomplish this as follows:

window.onclick = function(e) {
   var element = e.target;
   while (element !== document) {
      if (element.nodeName === 'DIV') {
         alert('Div clicked!')
      }
      element = element.parentNode;
   }
}

And that's it!

Let's try the code:

Live Example

So what do you say? Wasn't this easy?