Sunday, 11 April 2010

Javascript: stop event propagation on click event

Question:
How to stop my click event to propagate to the document level?

I have a click event on a link and one on the div container around it. How do I prevent the click event, that I handle in the click event handler on the link, to bubble up to the container?




Answer:
You must ask the event to stop its propagation.

Follow these steps:
  1. attache event handler function to onClick event
    <a href="someUrl" onClick="stopPropagation(event)" >CLICK ME</a>
    
  2. stop event propagation depending on browser
    stopPropagation = function (event) {
        if (!event)
            event = window.event;
        // that is for IE
        if (event.cancelBubble)
            event.cancelBubble = true;
        // this is for standard browsers  
        else
            event.stopPropagation();
    }
    

No comments: