Question

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!

Was it helpful?

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.

OTHER TIPS

You could do this

$(".class").mouseenter( function(){
$(this).css("edit css"); // you can use .animate instead of .css if you want
});
$(".class").mouseleave( function(){
$(this).removeAttr('style');
});
$(".class").click( function(){
$(this).addClass("setactiveclass");
});

So when you hover, a inline css is set and if you hover out of the div the inline style set by the jquery is removed.. And if you click on it. a hard class is set on it so it does not interfere with eachother.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top