CLiown
CLiown

Reputation: 13853

Remove class when move to next menu item

I have a simple nav made up of the following HTML;

<div class="inner">
<div class="button"><img class="portal" src="images/portalbutton.png" /></div>
<a href="#"><div class="prod_description">&nbsp;</div></a>
</div>

There are a number of items (All set to float left along side each other) to make up a nav bar.

When I hover over .button and/or .prod_description I want the .inner <div> to have the class .hover added to it. This is so I can set a background image around the whole thing (Kind of like highlighting the nav item).

I only then want to remove .hover when another .button or .prod_description is hovered over, in which case this nav item takes the .hover class.

Upvotes: 1

Views: 238

Answers (3)

J&#248;rn Schou-Rode
J&#248;rn Schou-Rode

Reputation: 38386

When I hover over .button and/or .prod_description I want the .inner <div> to have the class .hover added to it.

Unless your CSS is positioning things in a very clever way, this would be the same as hovering the .inner itself, right? If so, the task can be solves as easy as:

$('.inner').hover(function() {
    $('.inner').removeClass('hover');
    $(this).addClass('hover');
});

If my assumption about the positioning doesn't hold, the code will have to look more like this:

$('.inner .button, .inner .prod_description').hover(function() {
    $('.inner').removeClass('hover');
    $(this).parents('.inner').addClass('hover');
});

In the latter code sample, notice the use of parents() - not to be confused with parent().

Upvotes: 2

amurra
amurra

Reputation: 15411

Try this:

$(document).ready(function(){
  $(".button").hover(
   function () {
      $(".inner").removeClass("hover");
      $(this).parent(".inner").addClass("hover");
   },
   function () {}
 );
 $(".prod_description").hover(
   function () {
      $(".inner").removeClass("hover");
      $(this).parent("a").parent("inner").addClass("hover");
   },
   function () {}
 ); });

Upvotes: 2

wsanville
wsanville

Reputation: 37516

With this small change to your html, the Javascript will be a little easier to write:

<div class="inner">
    <div class="button"><img class="portal" src="images/portalbutton.png" /></div>
    <div class="prod_description"><a href="#">stuff</a></div>
</div>

Then, your Javscript function looks like this. When you hover an item, it removes the hover class from all items and applies it to the current one. That way, the hover class will stay, even when moving away from the item.

$(document).ready(function() {
            $('div.button, div.prod_description').mouseover(function() {
                $('div.inner').removeClass('hover');
                $(this).parent().addClass('hover'); //The HTML change was to allow the call to parent() to be the same
            });
        });

Upvotes: 1

Related Questions