views:

1361

answers:

1

Hi, 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!

A: 

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.

mwc
Simple is best!I got sidetracked by the idea of having a single style class to keep the same style for hovering and clicking, but defining two selectors and one style as follows:.active_hover, .active_click {...}Gives the desired result. Thanks!
KyokoHunter