I'm making a script in jQuery, and I have many click links click events. The thing is that I don't want the links I have click events for to do anything except the event, so I put an e.preventDefault();
at start of all my click events. But I have many click events, so is there a more simple way to just add the e.preventDefault();
to all the links click events? Remember I also have some links that I want to work as they should, so adding the e.preventDefault();
to all the links won't work, I only want to add it to links with click event.
-
is there any way to define, via a class-name or such, the group of `a` elements that you want to retain their normal function? – David Thomas Apr 10 '11 at 18:17
4 Answers
you can use jquery namespaced events
http://docs.jquery.com/Namespaced_Events
HTH
you can do something like this for the links you want to add a click event but prevent the default behaviour
$('a.someClass').bind('click.dontClick',function(e){
e.preventDefault();
});
and for the links you want the normal click behaviour
$('a.clickClass').bind('click.doClick',function(e){
//your event handling code here
});

- 30,950
- 5
- 68
- 101
-
Yes, but that way I need to add a class to each link, and I also don't want that... I want the e.preventDefault(); to be automatically added at start of every link click event. – Cokegod Apr 10 '11 at 19:08
You could try overriding the bind method, or the click method, before any of your binding code runs. Here I'm overriding the click method in a fairly hacky way. I would really recommend just calling preventDefault where you need it.
(function(){
var original = jQuery.fn.click;
jQuery.fn.click = function(){
// wrap your function in another function
var f = arguments[0];
arguments[0] = function(e) {
e.preventDefault();
f(e);
}
original.apply( this, arguments );
}
})();
Example in action: http://jsfiddle.net/k4jzb/

- 11,475
- 1
- 36
- 47
I would take @3nigma's answer a little further. Usually the links you don't want to do default actions on are like <a href="#">
So filter out these links so the page doesn't jump when clicked. I use jQuerys filter() function. Not sure if that is the best. What do you think?
$('a').filter(function(i) {
return $(this).attr("href") === "#";
})
.bind('click.dontClick',function(e){
e.preventDefault();
})
Example here: Filter a tags containing #

- 165
- 1
- 3
- 13
This SO answer details how to detect events on an element, but it looks like the asker took that answer and built a jQuery plugin for selecting elements based on their event listeners.
So you could use that plugin and then use some event delegation like so:
$(document).delegate('a:Event(click)', 'click', function (e) { e.preventDefault(); });
Warning: I've never used this plugin myself, and I'm not really familiar with custom jQuery CSS filters, so this might not actually work. At all.

- 1
- 1

- 42,000
- 6
- 53
- 67