1

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/

Leo
  • 2,061
  • 4
  • 30
  • 58

3 Answers3

6

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.

Nick Perkins
  • 1,327
  • 2
  • 12
  • 25
  • Works just fine, didn't really think of that, shame on me. anyway, thank you, sir – Leo Jan 08 '13 at 03:55
  • 2
    mouseout() will trigger when the mouse leaves child elements, which is often not desireable. mouseleave() is better. See: http://stackoverflow.com/questions/4258615/what-is-the-difference-between-jquerys-mouseout-and-mouseleave – Taz Jan 08 '13 at 03:55
1

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

Taz
  • 1,235
  • 9
  • 16
1

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'
  });
});
Sang Suantak
  • 5,213
  • 1
  • 27
  • 46