michael
michael

Reputation: 167

How to toggle a class immediately upon click (not after mouse button is released)

I'd like to change the color of my span element immediately when the user clicks on it - not have the color change occur after the mouse button is released.

Here's my CSS for the class I'm toggling:

span.active{
  color:#bdbcae;
}

Here's my "idea" for the jQuery, but this toggles the class after the click:

$("span").click(function() {
   $(this).toggleClass("active");
});

It's probably something basic, or maybe something more complex, but what kind of function do I use to achieve this?

Upvotes: 0

Views: 303

Answers (2)

haimlit
haimlit

Reputation: 2582

mousedown sounds like what you're looking for:

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

so this would probably be your code:

$( "span" ).mousedown(function() {
   $( this ).toggleClass( "active" );
});

Upvotes: 2

tymeJV
tymeJV

Reputation: 104785

Use mousedown

$("span").mousedown(function() {

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

Upvotes: 4

Related Questions