Course: JavaScript

Progress (0%)

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?

"I created Codeguage to save you from falling into the same learning conundrums that I fell into."

— Bilal Adnan, Founder of Codeguage