Search code examples
javascriptjqueryhtmlhtml5-history

How to implement a global click handler without conflicting with already defined events


I would like to bind a click event to all the elements inside a web page without getting conflicted with the events which are already defined. I' trying to use the following code to define the global click event.

$("body").click(function (event) {
}

I'm using this click event to figure out if it's a page redirect and to save that data into the html5 history object. What is the best way to implement such a logic in an already defined system?


Solution

  • <input type="button" onclick="buttonClick()" value = 'hey' />
    
    <script>
    $("body").click(function(){
        alert("hey body");
    });
    $("body").click(function(){
        alert("hey body 2");
    });
    
    function buttonClick(){
        alert("hey button");
    }
    </script>
    

    Check this simple test.

    Click on body will trigger "hey body" and "hey body 2".

    Clicking on the button will trigger "Hey button" "Hey body" and "Hey body2". The events are simply added on top of each other and every linked event get triggered.