Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

addClass on hover for multiple items

So I've been working on this script all day and all the examples I've seen just don't seem to do what I want. Here's my example CodePen. Try to hover over "MENUS" and over "SETTINGS". I'll try to explain the problem with words:

The Script:

var activeItem = $("#menu .active");
var items = $("#menu .main:not(.active)");

activeItem.addClass("active-2");

items.hover(function () {
    "use strict";
    activeItem.toggleClass("active-2");
});

$(document).mousemove(function (event) {
    "use strict";
    if ($(".sub-1").css("background-clip").toLowerCase() == "content-box") {
        $(".sub-1").parents(".main").addClass("active-2");
        $(".sub-1").parents(".main").css("background-color", "#CCC");
    } else {
        $(".sub-1").parents(".main").removeClass("active-2");
        $(".sub-1").parents(".main").css("background-color", "");
    }
});

The above code gives the blue line (class active-2) to the active item. In this case "HOME". The items variable counts all main menu items that are not active and is used to toggle blue line (active-2) from "HOME" when other items are hovered. So far so good.

The Problem:

I have submenu items (the dark-grey ones). When the mouse is anywhere over these submenu items I want to give the parent main item the blue line (active-2) until the mouse leaves, then return the blue line to the currently active item activeItem, in this case "HOME".

When there is only 1 subitem group (like the one under "MENUS"), it works. But when I added a second submenu group (under "SETTINGS") it broke. I'm looking for a way to make it so no matter how many submenu groups I have the main item's blue line should be visible when my mouse is over it's submenu items and return to activeItem when I'm no longer hovering it. If you delete one of the uls with class .sub-1 under "MENUS" or "SETTINGS" with the inspector it will start working again.

Why mousemove???

I tried to .addClass in .hover and .removeClass in it's callback function but that didn't work... Or maybe I'm just not doing it right? So basically the only way I could think of achieving this effect was with mousemove, checking for meaningless CSS properties that are given to subitems only when they are visible:

#menu li:hover > ul {
    left: auto;
    background-clip: content-box;
}

So... I have no idea how to make it work in a meaningful way. Please help.

Edit:

Provided CodePen link at the top of the question.

like image 767
Johny P. Avatar asked Jul 07 '17 18:07

Johny P.


1 Answers

Please in your codepen replace CSS line #329 with the following:

#menu li.main:hover > a:before, #menu .active > a:before {

And JS will be:

var activeItem = $("#menu .active");

items.hover(function () {
    activeItem.toggleClass("active");
});
like image 135
Kosh Avatar answered Oct 31 '22 14:10

Kosh