cybermotron
cybermotron

Reputation: 987

jquery: button mousedown state change

OK this should be easy but I can't seem to get it to work.

I have a button, when I click on it I want it to change state, but only for as long as the the button is being pressed, like any OS native button.

So here is my code...

$('button').live('mousedown', function(){

    $(this).addClass('down');

}).live('mouseup', function(){
    $(this).removeClass('down');
});

Looks simple enough right... but this doesn't work. When you click on it, the state does change... but it stays that way... the mouseup event only works the second time you click on it.

This also happens with toggleClass and when I execute the code from the focus/blur event.

What is going on here, and how can I make it work properly?

Upvotes: 1

Views: 3095

Answers (2)

user489419
user489419

Reputation: 71

The original solution posted by cybermotron written in jQuery works perfect for me on Chrome, Firefox and IE.

In case it does not work, perhaps setting a timeout of about 200ms on the mouseup function will improve the functionality. Not everything you want to do is a class.

Upvotes: 1

Just Jake
Just Jake

Reputation: 4848

You should consider using CSS instead, as it's much faster for display purposes than adding/removing a class via Javascript:

button:active { /* this is the mousedown pseudoelement */ }
input:focus, textarea:focus { /* this represents text input fields with focus */ }

Upvotes: 4

Related Questions