Alfred
Alfred

Reputation: 21406

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?

Upvotes: 1

Views: 4445

Answers (2)

Priyabrata
Priyabrata

Reputation: 649

$(function(){
    $("#b1").hover(function(){
        $("#switch").css('background-position','0px 10px');
    });
    $("#b2").hover(function(){
        $("#switch").css('background-position','0px 20px');
    });
    $("#b3").hover(function(){
        $("#switch").css('background-position','0px 30px');
    });
});

Upvotes: 0

Hussein
Hussein

Reputation: 42818

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/

Upvotes: 2

Related Questions