user1078494
user1078494

Reputation: 509

Change parent element background position on child hover

I'm trying to create a navigation menu which would change parent div background when hover on child li item. Actually, I just want to move the parent background.

Here's my code:

<div id="headerNav">
    <li class="navHome"><a href="index.php">Home</a></li>
    <li class="navServices"><a href="services.php">Services</a></li>
    <li class="navFaq"><a href="faq.php">FAQ</a></li>
    <li class="navGallery"><a href="gallery.php">Gallery</a></li>
    <li class="navContact"><a href="contact-us.php">Contact</a></li>
</div>

So, I have the #headerNav showing default background. When you hover over Services, I want move #headerNav background image 75px up. When you hover over FAQ, I want to move #headerNav background image 150px up, etc.

Can anyone help me?

Upvotes: 2

Views: 2360

Answers (3)

Brilliand
Brilliand

Reputation: 13714

jQuery can do this easily with the hover() function:

$("li").hover(function() {
    $(this.parentNode).addClass(this.className);
}, function() {
    $(this.parentNode).removeClass(this.className);
});

jsFiddle: http://jsfiddle.net/Zy68z/

Upvotes: 0

Samir Adel
Samir Adel

Reputation: 2499

You can do that using by putting a custom attribute on the li's that determine the number of pixels to move and use the jquery when hover on an item, get the attribute value then access it's parent to set it's background position using this attribute, this way it will be scalable menu and robust

$("#headerNav li").hover(function() {
    $(this).parent().css("background-position", $(this).attr("CustomAttributeName"));
})

Upvotes: 0

VisioN
VisioN

Reputation: 145458

Consider that li elements are list items, so its parent should be e.g. ul tag but not div. If we imagine valid HTML markup, you can use something like follows to operate background-position of the parent element. I used index() method for not hardcoding the logic.

$("#headerNav > li").hover(function() {
    var pos = "0 -" + ($(this).index() * 75) + "px";
    $(this).parent().css("background-position", pos);
}, function() {
    $(this).parent().css("background-position", "0 0");
});

DEMO: http://jsfiddle.net/rFhtP/

Upvotes: 3

Related Questions