I was wondering about that:
I have some links in my html file and to most of them I need to write in their click functions to not jump to the top of the page (which e.preventDefault() does that)ת I need to write that action aside from the functions that they actually do.
can I write something like that:
$('a').click(function(){e.preventDefault()})
Will it work? or will it create conflicts with the real functions if I will write like:
$('a').click(function(){e.preventDefault()});
$('a#goingToDoSomething').click(function(){console.log('just did it')})
I ask because I want to make my code better - but wasn't sure if that was the way.. thanks, Alon
Yes it will work, if you pass the normalised event object to the callback function:
$('a').click(function (e) {
e.preventDefault();
});
No, there won't be any conflicts (conflicts? huh?). You can bind extra click handlers to your links and they will work as expected.
The other answers are correct, but not as efficient as:
$('body').on('click', 'a', function(e){
e.preventDefault();
});
Edit:
$(document).on
will be even faster, but not tested it, should work though
requires jQuery 1.7+
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With