Monday, May 28, 2012

Change parent elements background image position on child mouseover

Demo: http://jsfiddle.net/rFhtP/

HTML

<ul 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>
</ul>

CSS

#headerNav {
    background: url(http://wordpress.deaction.com/wp-content/uploads/2011/08/cat-whatiscat.com_.jpg) no-repeat left top;
}

jQuery

$("#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");
});