简体   繁体   中英

Removing preventDefault and stopPropagation in javascript

Hi i need to prevent the default action when the user clicked on a element and prevent its default action only for that time and need to do some other action. For which i used

document.body.onclick = function (e) {
    e.preventDefault();
    e.stopPropagation();
}

But now the problem is, after i performing the above action i need to remove the preventDefault and stopPropagation , because none of the link(a href) is getting triggered after this. So how to undo this after performing it? Please note that it is a pure JavaScript code and im not using any library like jquery. So i can't use .bind and .unbind . Any idea on this would be greatly appreciated.

You can replicate the behavior of bind and unbind using addEventListener and removeEventListener

function stopIt(e) {
  e.preventDefault();
  e.stopPropagation();
}

document.body.addEventListener("click", stopIt);

// then later

document.body.removeEventListener("click", stopIt);

Note: IE <= 8 doesn't support addEventListener and removeEventListener , so you'll need to use attachEvent as mentioned here - https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener#Compatibility

Don't bind the event to the body, bind the event to the element you need to prevent:

document.getElementById('theTarget').onclick = function(e) {
    // ...
}

If I understand your requirement correctly, I'm afraid you cannot undo the e.preventDefault(); . But by default, the handler function will be executed before performing the default action. So in your case, you just don't need the e.preventDefault(); at all. And remember to attach the event listeners only to <a> tags

var aTags = document.getElementsByTagName("a");

for (var i=0;i<aTags.length;i++){
    aTags[i].onclick = function (e) {
       // just perform your action here, don't need e.preventDefault();
    }
}

Here is the working solution for breaking or rollback the stopImmediatePropagation():

Do unbind

$("#mydiv").unbind();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM