Home > other >  remove click-event on an element and keep the link redirect jquery
remove click-event on an element and keep the link redirect jquery

Time:10-20

I have this a_tag element: <a href="Mywebsite/test/cart/" title="View cart">View cart</a> which is bound to different click events by outer plugins used on my website, I tried to remove all the other click events using this, $('.added_to_cart').click(function() { return false; }); Which is working fine but it is also disabling the href link redirection.

Is there a way to remove all the click events and keep the href link redirection ??

CodePudding user response:

return false in event is almost the same as ev.preventDefault() that is mean that all default events will not be fired.

For prevent other events, but not default behaviour (redirect by link), you need to stop propagation of event:

$('.added_to_cart').click(function(ev) { ev.stopImmediatePropagation(); });

CodePudding user response:

You can use redirection by javascript, try :

$('.added_to_cart').click(function() { window.location.href = 'Mywebsite/test/cart'; });

CodePudding user response:

That is not possible without intercepting addEventListener calls and keep track of the listeners or use a library that allows such features unfortunately. It would have been if the listeners collection was accessible but the feature wasn't implemented.

The closest thing you can do is to remove all listeners by cloning the element, which will not clone the listeners collection.

var el = jQuery('.added_to_cart')
var elClone = el.clone()
el.replaceWith(elClone)

To do it in a single line:

jQuery('.added_to_cart').replaceWith(jQuery('.added_to_cart').clone())

You can check a similar issue here: Remove All Event Listeners of Specific Type

  • Related