Tag Archives: addEventListener

Creating Page Links Using getElementsByTagName and addEventListener

The following is a tutorial on how to make all div elements clickable on a web page.  Handle click events on all div tags or on any specific element type in your HTML.

Do you have a need on your HTML page to create links using all the elements of a specific type.  For example, you want all “div” elements to become links that provide some sort of action in javascript.  This can be accomplished using two main functions available in javascript.  The getElementsByTagName and addEventListener functions.

The way this is handled is to create an anonymous function that adds event listeners to your page when it loads.  These event listeners then pass the event to a function that uses a switch statement and the div ID to set specific logic for each div.

We start by creating a basic HTML page that ends with the call to our script as seen below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<html>
 
<head>
	<title>Make Divs Clickable!</title>
</head>
<body>
	<div style="background-color: black" id="FirstDiv">
              <h2 style="color: white">Click this div to say: FirstDiv</h2>
        </div>
 
	<div style="background-color: black" id="SecondDiv">
              <h2 style="color: white">Click this div to say: SecondDiv</h2>
        </div>
 
	<div style="background-color: black" id="ThirdDiv">
              <h2 style="color: white">Our third div is not handled</h2>
        </div>
 
	<script type="text/javascript" src="test.js" ></script>
 
</body>
 
</html>

Next, we create the following anonymous function in our javascript file which adds the event listeners and sets up the handling of the different div ID’s.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//create an anonymous function
(function() {
 
	//get all of our div elements
	var links = document.getElementsByTagName("div");
 
	//add an event handler to all of the page elements
	for( var i = 0, len = links.length; i < len; i++) {
		//add an event listener to our div
		links[i].addEventListener("mousedown", elementClickHandler);
 
 
	}
 
 
	function elementClickHandler(event) {
		//get the ID from the event
		var elementID = event.currentTarget.id;
 
		//do something based on the ID
		switch(elementID) {
		case "FirstDiv":
			//do something
			alert(elementID);
			break;
		case "SecondDiv":
			//do something
			alert(elementID);
			break;
		default:
			//do something
			alert("Some other div not Handled");
		}
	}
 
})();

That’s all there is to it. If you would like to download the ZIP file for this example, it is available via the link Make-div-Elements-Clickable.