NaveenBharadwaj NaveenBharadwaj - 1 year ago 71
Javascript Question

Stop propagation doesn't work

I have the below JQuery

. I want to stop all navigations on a web page.

$(document).click(function(event) {
event.cancelBubble = true;
return false;

When I use this on Facebook Login page, it stops all navigations. But in Google home page, "I'm Feeling Lucky" button still navigates to next page. How do I avoid it?

I'm using JavaFX browser by the way. It is similar to Safari browser.

Answer Source

If I load the Google search page, and execute this at the console:

  function (ev) { ev.stopPropagation(); ev.preventDefault(); },

then I cannot click the "I'm Feeling Lucky" button anymore. The key is to use the third parameter and set it to true. Here is what MDN [says] about it:

useCapture Optional

If true, useCapture indicates that the user wishes to initiate capture. After initiating capture, all events of the specified type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.

(Emphasis added.)

What you tried to do does not work because your event handler is on document, and thus will be called after any event handlers on the children of the document. So your handler cannot prevent anything.

With useCapture set to true, you can operate on the event before it gets a chance to be passed to the child element. I do not know of a way to have jQuery's event handlers work in the way you get with useCapture. Barmar's answer here says you can't use jQuery to set such handler. I'm inclined to believe him.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download