How to Disable Click Event Outside a Div in JavaScript

Hello devs,

In this tutorial, I am going to share with you that how to disable click event outside a div in javascript. So from this tutorial, you will learn to disable click events outside a div javascript. 

Sometimes in our application on client-side, we need to disable some portion of the section in JavaScript. From this example, you will learn that way to disable click on div javascript.

Example code:

document.addEventListener("click", (evt) => {
    const flyoutElement = document.getElementById("flyout-example");
    let targetElement = evt.target; // clicked element

    do {
        if (targetElement == flyoutElement) {
            // This is a click inside. Do nothing, just return.
            document.getElementById("flyout-debug").textContent = "Clicked inside!";
            return;
        }
        // Go up the DOM
        targetElement = targetElement.parentNode;
    } while (targetElement);

    // This is a click outside.
    document.getElementById("flyout-debug").textContent = "Clicked outside!";
});

 

Hope it can help you.

 

author-image
Facebook Github
A web enthusiastic, a self-motivated full-stack software engineer from Dhaka, Bangladesh with experience in developing applications using Laravel , React and Vue js