ONYX
ONYX

Reputation: 5859

Keep hover state active across divs

I want to know how you keep the hover state of div element active accross multiple div elements. So if i hover over Menu-item 1 then go to Menu-item 6 Menu item 1 is active while menu item 6 is active then I'd goto menu item 9 and thats active so my previous Menu Items are active.

CSS:

.menuitem-active {
     background-color: #ff9900;
}
.menuitem {
     background-color: #ffffff;
}

HTML:

<div class="container">
    <div class="menu">
        <div class="menu-item">Menu Item 1</div>
        <div class="menu-item">Menu Item 2</div>
        <div class="menu-item">Menu Item 3</div>
        <div class="menu-item">Menu Item 4</div>
    </div>
</div>
<div class="container">
    <div class="menu">
        <div class="menu-item">Menu Item 5</div>
        <div class="menu-item">Menu Item 6</div>
        <div class="menu-item">Menu Item 7</div>
        <div class="menu-item">Menu Item 8</div>
    </div>
</div>
<div class="container">
    <div class="menu">
        <div class="menu-item">Menu Item 9</div>
        <div class="menu-item">Menu Item 10</div>
        <div class="menu-item">Menu Item 11</div>
        <div class="menu-item">Menu Item 12</div>
    </div>
</div>

Javascript:

$('.container .menu .menu-item').mouseenter(function(){

});

Upvotes: 0

Views: 2328

Answers (4)

Rudie
Rudie

Reputation: 53881

You can do this in pure CSS(3): http://jsfiddle.net/rudiedirkx/W8McN

I added -webkit- and -moz- vendor prefixes, because (unstandardized) transitions are necessary for this.

Upvotes: 1

David Thomas
David Thomas

Reputation: 253486

You could try this:

$('.container > .menu > .menu-item').hover(

function() { // first function, the 'mouseenter'
    $(this).addClass('active');
},
function() { // the second function, the 'mouseleave'
    $(this).removeClass('active')
});

JS Fiddle demo.

Incidentally, please pay attention to your quoting of attribute values, the class="container left an un-termintated string, which can cause problems all by itself.

Upvotes: 0

DarthJDG
DarthJDG

Reputation: 16591

Assuming you define a selected class for the hover effect:

$('.container .menu .menu-item').mouseenter(function() {
    $(this).siblings().removeClass('selected');
    $(this).addClass('selected');
});

The siblings() function will select the menu items only within the current element's parent.

Upvotes: 2

robx
robx

Reputation: 3123

you might want to close off some of those class container since it was left unclosed. Anyhow, mouseenter doesn't really seem practical since the divs will span 100% and as you move down, every one of them will become active.

Assuming you set an active style in css just change its attribute to "active" or "item" I'd recommend changing it to click event

$('.container .menu .menu-item').click(function() {
    $(this).attr("class","menu-active");
});

Here is an example http://jsfiddle.net/robx/RsNw3/

Upvotes: 1

Related Questions