rdp
rdp

Reputation: 2088

Changing background image position on hover using javascript

I have 10 links. I am using a separate sprite sheet for a single link which consist of active, hover and inactive link image. I want to know how can i change the background-postion from javascript. I know how to do this in css but for 10 different links i think javascript will a better option as i can use the same code for every link. Waiting for your suggestions.

Upvotes: 2

Views: 21643

Answers (2)

pixeline
pixeline

Reputation: 17974

you are mistaken: this should be done in CSS, its the fastest to render, even though it takes more initial declarations. Just make sure your CSS is optimized.

.links{
background:transparent url(sprite.png) 0 0;
}

#link1{
background-position: 0 0;
}
#link1:hover{
background-position: 0 -50px;
}

#link2{
background-position: 100px 0;
}
#link2:hover{
background-position: 100px -50px;
}

And the HTML:

<a class="links" id="link1" href="#">link 1</a>
<a class="links" id="link2" href="#">link 2</a>

If you really, really want to do it in javascript, you're looking for the style() method. See W3Schools on style() and backgroundPosition

Upvotes: 7

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195982

The best is to use css, even for multiple images.

If the sizing is the same for the sprites of the 10 links, you can make a rule that is agnostic of the image and just repositions the background image

a.someclass:hover{
  background-position:Xpx Ypx;
}

and apply the someclass (or whatever you name it) to all your links...

Upvotes: 3

Related Questions