Search code examples
jqueryclickmouseentermouseleave

prioritizing a jquery function to override another


Using jQuery, I am trying to program 2 different kinds of feedback within search menu buttons. The issue is that the 2 require conflicting code:

First, show that the red buttons are "clickable" by changing one to a different color (blue) when the mouse enters it, and then changing it back to the original color (red) when the mouse leaves it:

$('.buttons').mouseenter(function() {
    $(this).css("background-color", "blue");
});
$('.buttons').mouseleave(function() {
    $(this).css("background-color", "red");
});

Second, show that a certain button is "clicked" by changing the button to a 3rd color (yellow). I want the button to remain yellow until a new/different button is clicked. When that happens, I want the newly clicked button to change to yellow, and all other buttons to revert back to the original color (red).

$(".buttons").click(function() {
$(".buttons").css("background-color", "red");
$(this).css("background-color", "yellow");
});

This all works nicely until the mouse leaves the clicked button to move to another. When this happens, mouseleave changes the yellow button back to red.

Is there a way to prioritize jQuery commands? Is there another function I should use instead? Thanks so much in advance!


Solution

  • You should use class instead of .css() function. It is much simpler. Use something like this :

    $('.buttons').hover(function(){
        $(this).toggleClass('hover');
    }).on('click', function(){
        $('.buttons').removeClass('click').filter(this).addClass('click');
    })
    

    With those css :

    .buttons{
        background-color : red;
    }
    
    /*
    Could also be .buttons:hover an then remove the JS
    Much more efficient
    */
    .buttons.hover{
        background-color : blue;
    }
    
    .buttons.click{
        background-color : yellow;
    }
    

    Fiddle : http://jsfiddle.net/Re9bj/12/