Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 797
Alon Avatar asked Jan 19 '23 03:01

Alon


2 Answers

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.

like image 179
karim79 Avatar answered Jan 26 '23 00:01

karim79


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+

like image 45
Andrew Bullock Avatar answered Jan 25 '23 22:01

Andrew Bullock