Can I write e.preventDefault () using jQuery for all the links in my code?

I was wondering what:

I have some links in my html file, and for most of them I need to write clicks in my functions so as not to go to the top of the page (which does e.preventDefault ()) ת I need to write this action except for the functions that they are on actually do.

I can write something like this:

$('a').click(function(){e.preventDefault()}) 

Will this work? or it will create conflicts with real functions if I write like:

 $('a').click(function(){e.preventDefault()}); $('a#goingToDoSomething').click(function(){console.log('just did it')}) 

I ask because I want to improve my code, but was not sure that it was. thanks, Alon

+4
source share
3 answers

Yes, this will work if you pass a normalized event object to a callback function:

 $('a').click(function (e) { e.preventDefault(); }); 

No, there will be no conflicts (conflicts? Yes?). You can bind additional click handlers to your links, and they will work as expected.

+6
source

Other answers are correct, but not as effective as:

 $('body').on('click', 'a', function(e){ e.preventDefault(); }); 

Edit:

 $(document).on 

will be even faster, but not tested, should work, although

jQuery 1.7+ required

+2
source

It should work fine if you pass the event object to the click handler. try it

 $('a').click(function(e){e.preventDefault()}) 
+1
source

Source: https://habr.com/ru/post/1384733/


All Articles