Leo
Leo

Reputation: 2103

Mouseup and Mousedown

So I want the buttons to change style when mouse is down, and return to previous when it goes up. I have this code:

$('#divMenu > #menu li a').mousedown(function(){
  $(this).css({
  'font-size': '25px',  
  'color': 'red'     
  });               
}).mouseup(function(){
  $(this).css({
  'font-size': '30px',  
  'color': 'black'     
  });               
});

The problem is, that when I have mouse down, but take it away of my object and not release immediately, font size and color stays 25px and red. What should I do to pass that?

EDIT: JsFiddle here: http://jsfiddle.net/h64Uz/

Upvotes: 1

Views: 10810

Answers (3)

Sang Suantak
Sang Suantak

Reputation: 5265

This should work (assuming you are using jQuery version 1.7 or above):

$('#divMenu > #menu li a').on("mousedown", function () {
  $(this).css({
    'font-size': '25px',
      'color': 'red'
  });
}).on("mouseup mouseout", function () {
  $(this).css({
    'font-size': '30px',
      'color': 'black'
  });
});

Upvotes: 1

Taz
Taz

Reputation: 1315

jQuery has a mouseleave() event you can use to supplement the existing code:

Upvotes: 1

Nick Perkins
Nick Perkins

Reputation: 1327

You need to use a mouseout as well.

$('#divMenu > #menu li a').mousedown(function(){
  $(this).css({
  'font-size': '25px',  
  'color': 'red'     
  });               
}).mouseup(function(){
  $(this).css({
  'font-size': '30px',  
  'color': 'black'     
  });               
}).mouseout(function(){
  $(this).css({
  'font-size': '30px',  
  'color': 'black'     
  });               
});

Your event code sets the css when the mouse is clicked. Once you move away it can't register a mouseup. But on leaving it will register a mouseout event.

Upvotes: 6

Related Questions