Home > Back-end >  Onclick is triggered even the click function is not added yet
Onclick is triggered even the click function is not added yet

Time:12-12

Whenever I click the start button, the click event on the html is also triggered. Why is it happening?

HTML:

        <button id="start-button">Start</button>

JavaScript:

const start = () => {
    $("html").on("click", function(){
        console.log("click")
    });
};


const loadPage = () => {
    $("#start-button").on("click", function(){
        console.log("start")
        start();
    });
}

$(window).on("load", loadPage);

I assume that the onclick function is not added to the html element yet when I click the start button, but it seems my assumption is wrong, anyone has ideas?

CodePudding user response:

I had the same question almost 4 years ago. The accepted answer was very helpful; but the simple answer is that, even though the event on "html" isn't added until the mouse event on "#start-button" fires, the new listener is added before that first event bubbles up the DOM, such that, when it reaches "html", the new event listener has already been registered and it "hears" the same mouse event.

You can stop the bubbling with event.stopPropagation() and you may already know that. It is a bit unexpected, at first, to learn that an event listener can be added to an element "higher up" the DOM during the bubbling phase such that it can fire if and when the bubbling reaches it.

CodePudding user response:

Javascript has inherent nature of bubbling events all the way up to the root node of the HTML.

Read more about it here. https://www.google.com/search?q=event bubbling in javascript&rlz=1C5CHFA_enIN988IN988&oq=event bubbl&aqs=chrome.1.0i512l2j69i57j0i512l7.2669j0j7&sourceid=chrome&ie=UTF-8

You can prevent events from bubbling up using https://developer.mozilla.org/en-US/docs/Web/API/Event/stopPropagation

CodePudding user response:

Since you're using this following line of code:

$(window).on("load", loadPage);

It automatically calls the method loadPage, whenever you are clicking the button. Because clicking that button reloading the window and hence on window's loading it calls "LoadPage" and from there this following code gets triggered:

$("#start-button").on("click", function(){...})
  • Related