Search code examples
javascriptjqueryhtmlmouseout

trying to prevent mouseout after link is clicked


I have a navigation with mouseover and mouseout animations. They work. I also have a statement for the click listener that adds a CSS class. The class sets the height of a div, the issue is that the mouseout also alters this div. So I'm trying to figure out a way to disable the mouseout listener when the link is clicked.

I tried to unbind it with no luck

js

var currentDiv;

function slideMenu(e) {

if(e.type === "mouseover"){
    // console.log("mouseover");
    TweenMax.to($(this).find('div') , 0.25, {height:20});
}
else if(e.type === "mouseout"){
    // console.log("mouseout");
    TweenMax.to($(this).find('div') , 0.25, {height:1});
}
else if(e.type === "click"){
    console.log("click");

    if (currentDiv !== undefined){
        $(currentDiv).removeClass("selected");
    }

    currentDiv = $(this).find('div');
    $(currentDiv).addClass("selected");

    $(currentDiv).unbind('mouseout'); // not working



}
}

$(".menu a").click(slideMenu);
$(".menu a").mouseover(slideMenu);
$(".menu a").mouseout(slideMenu);

css

.selected{
    height: 20px;
}

Solution

  • Would this accomplish your goal? Instead of worrying about the binding of click events, you could just check the "selected" class before you do anything else within that click event. Like the following...

    var currentDiv;
    
    function slideMenu(e) {
    
        if(e.type === "mouseover"){
            // console.log("mouseover");
    
            var child_div = $(this).find("div")
    
            if (!$(child_div).hasClass("selected")) {
                TweenMax.to($(this).find('div') , 0.25, {height:20});
            } else {
                $(child_div).attr("style", "") // remove inline styles attr, so that height is based on css instead of JS
            }
        }
        else if(e.type === "mouseout"){
            // console.log("mouseout");
    
            var child_div = $(this).find("div")
            if (!$(child_div).hasClass("selected")) { // check to see if selected/clicked on
                TweenMax.to($(this).find('div') , 0.25, {height:1})
            } else {
                $(child_div).attr("style", "") // remove inline styles attr, so that height is based on css instead of JS
            }
        }
        else if(e.type === "click"){
            console.log("click", this);
    
            if (currentDiv !== undefined){
                    $(currentDiv).removeClass("selected");
            }
    
            currentDiv = $(this).find('div');
    
            $(currentDiv).addClass("selected");
        }
    }
    
    $(".menu a").click(slideMenu);
    $(".menu a").mouseover(slideMenu);
    $(".menu a").mouseout(slideMenu);