Detecting a click on a element in DOM

As web developers some times we need to detect clicks on elements of our DOM to enhance experience with our site. Here is a one simple way we can achieve that.

In this tutorial I have demonstrated how to detect a click on a Image in side a div element.
you can find images used in this tutorial from here.

Here is the HTML for the tutorial

<!DOCTYPE html>

<html>
<head>
    <style>
        .imagegrid{
            border: 3px solid black;
            padding: 10px;
        }
        
        img{
            border: 1px solid red;
            margin: 10px;
        }
    </style>
</head>

<body>
    <h2>Image Grid</h2>
    <div class="imagegrid">
        <img src="Images/facebook.ico">
        <img src="Images/google.ico">
        <img src="Images/Linkedin-icon.png">
        <img src="Images/twitter-icon.png">
    
    </div>  
</body>    
</html>



Java Script code to detect the clicks

var myNode= document.querySelector('.imagegrid');

myNode.addEventListener("click",function(e){

  if(e.target.tagName==="IMG"){
   alert(e.target.src+" clicked");
  } 


},false); 


What happen in the script

  1. Get an element which has "imagegrid" class to myNode variable.
  2. Add an event listener to that myNode element fire up when a click happen.
  3. Alert a message if tagName of a click event (detect by event listener on myNode variable) is equal to "IMG".

In this way you can detect a click on an "img" element as well as other elements in your DOM.
In this tutorial we just alert a message with source of clicked image, but you can do what ever you want after detecting a click on an element like,

  • Taking user to another page
  • Display a larger image of the image
  • Give a hint to the user
This kind of small things give a better experience to the user of your site.


NOTE: CSS parts in the head is added to display limits of images and div with a border

No comments:

Post a Comment