Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing background image position on hover using javascript

Tags:

javascript

css

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.

like image 965
rdp Avatar asked Jul 11 '26 07:07

rdp


2 Answers

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

like image 89
pixeline Avatar answered Jul 13 '26 22:07

pixeline


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

like image 36
Gabriele Petrioli Avatar answered Jul 13 '26 21:07

Gabriele Petrioli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!