2

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.

2
  • Can you show us your HTML and CSS, it's hard to answer otherwise. Commented Jan 3, 2011 at 9:03
  • Are you using any JavaScript library? Commented Jan 3, 2011 at 9:07

2 Answers 2

7

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

Sign up to request clarification or add additional context in comments.

1 Comment

typo in css #link12 sould be #link2
3

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...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.