Understanding JavaScript Events with an Image Gallery

Understanding JavaScript Events with an Image Gallery

In this tutorial, we'll dive into JavaScript events using a simple image gallery. We’ll explore various event-handling techniques, the concept of event propagation, and how to manage default behaviors in the browser.

HTML Structure

Our HTML code consists of a simple list of images and a link:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML Events</title>
</head>
<body style="background-color: #414141; color: aliceblue;">
    <h2>Amazing image</h2>
    <div>
        <ul id="images">
            <li><img width="200px" id="photoshop" src="https://images.pexels.com/photos/3561339/pexels-photo-3561339.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt="photoshop"></li>
            <li><img width="200px" id="japan" src="https://images.pexels.com/photos/3532553/pexels-photo-3532553.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt=""></li>
            <li><img width="200px" id="river" src="https://images.pexels.com/photos/3532551/pexels-photo-3532551.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt=""></li>
            <li><img width="200px" id="owl" src="https://images.pexels.com/photos/3532552/pexels-photo-3532552.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt="" onclick="alert('owl clicked')"></li>
            <li><img width="200px" id="prayer" src="https://images.pexels.com/photos/2522671/pexels-photo-2522671.jpeg?auto=compress&cs=tinysrgb&w=1600&lazy=load" alt=""></li>
            <li><a style="color: aliceblue;" href="https://google.com" id="google">Google</a></li>
        </ul>
    </div>
    <script src="script.js"></script>
</body>
</html>

This is what final output looks like:

JavaScript Event Handling

Adding an Event Listener: Instead of using inline event handlers (which can become unmanageable as your application grows), we use addEventListener to handle events. This provides better separation of HTML and JavaScript and allows for more flexibility in managing events.

document.getElementById("owl").onclick = function() {
    alert("owl clicked");
};
// Problem with this approach: as we are applying "onclick" event on an id,
// there can be some problems with onclick as we don't get much information.

// We should actually use EventListeners because they not only provide onclick 
//functionality but also provide the ability of propagation.

//other methods used before onclick
// "attachEvent()" and jQuery - "on"

document.getElementById("owl").addEventListener("click", function(e) {
    alert("owl clicked by best approach");
}, false);

// This 3rd parameter "false" is a default parameter, so we can write it or not, 
//it's up to you, but sometimes some applications require this 3rd parameter, 
//and without this 3rd parameter those applications cannot be completed.

Exploring the Event Object

The event object contains information about the event that occurred. By logging the event object, you can see all the properties and methods available to interact with the event.

document.getElementById('owl').addEventListener("click", function(e){
    console.log(e);
});

We got a pointer event and which is an Object, and inside this we get many events and few important one are browser events and environment events.

Event Propagation

There are 2 context of event propagation:

  1. Event bubbling

Event bubbling is the process where an event starts from the deepest element and then bubbles up to the outer elements. Here, clicking on an image inside the <ul> triggers the event on both the image and the <ul>.

document.getElementById('images').addEventListener("click", function(e){
    console.log("clicked inside the ul");
}, false);

document.getElementById('owl').addEventListener("click", function(e){
    console.log("owl clicked");
}, false);
//outputs When clicking on the owl image, the console outputs:
owl clicked
clicked inside the ul

//when you click on any other image than owl, then it outputs:
clicked inside the ul
  1. Event Capturing:

Event capturing is the opposite of bubbling. The event starts from the outermost element and goes down to the target element.

document.getElementById('images').addEventListener("click", function(e){
    console.log("clicked inside the ul");
}, true);

document.getElementById('owl').addEventListener("click", function(e){
    console.log("owl clicked");
}, true);

Now, when you click on the owl image, the console outputs:

clicked inside the ul
owl clicked

Preventing Event Propagation and Default Behaviors

  1. Stopping Propagation:

Sometimes you might want to stop the event from propagating. The stopPropagation method can be used to prevent further propagation of the current event.

document.getElementById('owl').addEventListener("click", function(e){
console.log("clicked inside the ul");
}, false)

document.getElementById('owl').addEventListener("click", function(e){
    console.log("owl clicked");
    e.stopPropagation();
}, false);

  1. Preventing Default Behavior:

To prevent the default behavior of an element (like following a link), use the preventDefault method.

document.getElementById('google').addEventListener("click", function(e){
    e.preventDefault();
}, false);

Removing Elements on Click (Project-based)

To remove an element when clicked, you can use the remove method.

document.querySelector('#images').addEventListener('click', function(e){
    console.log(e.target.parentNode);
    let removeIt = e.target.parentNode;
    removeIt.remove();
    // Another way to remove:
    // removeIt.parentNode.removeChild(removeIt);
});

However, if you click on any bullet or list item dot, the whole list will be cleared. To prevent this, ensure you only remove elements when clicking on an image or link:

document.querySelector('#images').addEventListener("click", function(e){
    console.log(e.target.tagName);
    if(e.target.tagName === "IMG" || e.target.tagName === "A"){
        let removeIt = e.target.parentNode;
        removeIt.remove();
    }
});

Conclusion

Understanding and handling events efficiently is crucial for creating interactive web applications. By using addEventListener, exploring event propagation, and managing default behaviors, you can build more robust and maintainable applications. This simple image gallery project provides a good starting point for mastering JavaScript events.