Batman
Batman

Reputation: 6353

Highlighting a single item in a list menu with many items

I have a navigation menu and I'm trying to do two things. When I hover 1 list item I'm trying to get that single item to be highlighted, if I click on a single item, I'm trying to make a certain color or style to be applied indicating that this item is currently in focus or active. If I select another, the current item deactivates and the newly selected item becomes active.

This is the CSS I tried but right now all items are being highlighted as soon as I hover any list item, instead of just one:

#listContainer{

      margin-top:15px;
    }

#expList ul, li {
    list-style: none;
    margin:0;
    padding:0;
    cursor: pointer;    
}
#expList p {
    margin:0;
    display:block;
}
#expList p:hover {
    background-color:#121212;
}
#expList li {
    line-height:140%;
    text-indent:0px;
    background-position: 1px 555555px;
    padding-left: 20px;
    background-repeat: no-repeat;
    margin-bottom: 5px;
}
#expList ul{
    margin-top: 5px;
}
#expList li:hover{
    background-color: #eee; This is where the problem is
}

/* Collapsed state for list element */
#expList .collapsed {
    background-image: url('https://hosted.compulite.ca/kc/MD/SiteAssets/collapsed.png');
}
/* Expanded state for list element
/* NOTE: This class must be located UNDER the collapsed one */
#expList .expanded {
    background-image: url('https://hosted.compulite.ca/kc/MD/SiteAssets/expanded.png');
}

Here's a JSFiddle with most of the code http://jsfiddle.net/aHSmy/1/

Upvotes: 0

Views: 220

Answers (2)

Sebsemillia
Sebsemillia

Reputation: 9476

You have to target your li items more accurately. Since your html structure is "ul -> li -> ul -> li with links" and your css just targets the first li which contains all the links, they of course all get applied the style when hovered. A more correct css targeting would be:

#expList ul li:hover{
    background-color: #eee;
}

and if you want to target the active/focus state, you must use css pseudo class selectors like :active. (read more about them here: css-tricks.com/pseudo-class-selectors), or if you want to use them long term while your user continues using the current page, use the jQuery script Paulie_d gave you.

Upvotes: 1

Paulie_D
Paulie_D

Reputation: 115046

Define an active class in your css and then use Jquery to apply and remove it

$(function() {
   $("li").click(function() {
      // remove classes from all
      $("li").removeClass("active");
      // add class to the one we clicked
      $(this).addClass("active");
   });
});

Codepen Example

Upvotes: 1

Related Questions