Question

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/

Was it helpful?

Solution

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.

OTHER TIPS

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

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'
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top