Search code examples
javascriptjqueryjquery-ui

Change background-position on hover using jQuery


I have divs on my page as below:

<div id="switch">
<div id="b1"></div>
<div id="b2"></div>
<div id="b3"></div>
</div>

with styling as:

#switch{
    background-position: 0px 0px;
    width: 300px;
    height: 100px;
    background-image: url(test.png);
    background-repeat: no-repeat;
}
#b1{
  width: 100px;
  height: 100px;
}
#b2{
  width: 100px;
  height: 100px;
  margin-left: 100px;
  margin-top: -100px;
}
#b3{
  width: 100px;
  height: 100px;
  margin-left: 200px;
  margin-top: -100px;
}

I want to change background-position to background-position: 0px -100px;, background-position: 0px -200px; and background-position: 0px -300px; when user hover on b1, b2, and b3 respectively.

You can see my fiddle here.

How can I make this possible?


Solution

  • var $switch = $('#switch');
    $('#b1').hover(function() {
        $switch.css({
            backgroundPosition: '0px -100px'
        })
    }, function() {
        $switch.css({
            backgroundPosition: '0 0'
        })
    }
    )
    

    This is done for #b1, you can do the same for others.

    Check working example at http://jsfiddle.net/MFJDE/3/