Charlie Chaplin
Charlie Chaplin

Reputation: 97

Is there a way to detect mouse press in jQuery?

I want to add a class to a link when it is clicked, but I can't use:

$('a.someLink').click(function() {
   // code
});

since click seems to detect when a user clicks and lets go of the mouse clicker on an element. I need to add the class as soon as the user has clicked on the element, even before he lets ago of the mouse clicker and after he lets go I need the class to be removed.

Basically I'm trying to mimic css's active state on links:

a:active

How can this be done?

Upvotes: 1

Views: 313

Answers (5)

Gonzalo
Gonzalo

Reputation: 166

With $('a.someLink').mousedown() you can add the class, and then with $('a.someLink').mouseup() you can remove it.

Upvotes: 1

ShankarSangoli
ShankarSangoli

Reputation: 69905

Try mousedown which is triggered even before click event.

$('a.someLink').mousedown(function() {
   // code
});

Upvotes: 0

Jayantha Lal Sirisena
Jayantha Lal Sirisena

Reputation: 21366

$('a.someLink').mousedown(function() {
 //code
});

http://api.jquery.com/mousedown/

Upvotes: 1

Brian Glaz
Brian Glaz

Reputation: 15666

You can use $('a.someLink').mousedown(function() { //code }); instead

Upvotes: 3

austinbv
austinbv

Reputation: 9491

mousedown() would be what you are looking for in the jQuery docs

Upvotes: 6

Related Questions