Search code examples
jqueryclasstogglemouseovermouseout

jquery: Toggle class on mouseover/mouseout of element, but keep class if click inside element?


suspect I'm trying to be too clever for my own good with this one!

I'm working on a jQuery plugin function that will toggle a class on/off on an element when you hover in/out, but doesn't remove the class if you click inside the element before hovering out and doesn't toggle if the element already has that class before hovering in.

I tried coming up with the following:

    $.fn.showHover = function(settings) {
    this.bind('mouseover', function hoverIn(){
        if ($(this).hasClass('active') == false) {
            $(this).addClass('active');
            $(this).bind('click', function getFocus(){
              $(this).unbind('mouseout', hoverOut);
            })
            $(this).bind('mouseout', function hoverOut(){
              $(this).removeClass("active");
              $(this).unbind('click', getFocus);
            })
        }
    })
    return this;
};

...the idea if you hover out before clicking, remove the class and unbind click - if you click before hovering out, unbind mouseout and the class never gets removed.

Obviously (since I'm asking here for help!) it doesn't work - the class gets removed whether I click inside the element before hovering out or not.

Can anybody point out why it's failing, and possibly suggest a better way around it? Thanks!


Solution

  • If changing the appearance of the element is your goal through CSS, one easy solution is to simply add another selector, with a different name.

    .active_hover,
    .active_click { ... }
    

    Then bind the hover/unhover event to add/remove the "active_hover" class, and the click event to add the "active_click" class.