31 August 2011

Javascript - Stop an event from bubbling up

In javascript, when you handle an event, allowing this event to bubble further up afterwards may cause undesirable effects.

I had some HTML that was created when clicking a butten and hidden when clicking anywhere but on that HTML itself. The buttons click event created the HTML, which was then immediately removed again because the click event bubbled on triggering the buttons parent, who then called for the removal.

The solution is to stop the event from continuing after being processed by calling this function in your own click handler:
function stopPropagation(e){
  var e = e || event; //Because of IE
  e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true; //Cancel the event
}

This solution however did not seem te work in Firefox. When using jQuery though, there is one that does:
e.stopImmediatePropagation();

No comments:

Post a Comment