sveti petar
sveti petar

Reputation: 3797

Set background position of image with Javascript

When a user clicks a link which has an image as a background, I need an onClick event that changes the background position of it. This is the link:

<a href="#" id="favorite_1" class="favorite" onClick="favoriteBusiness(1);">Favorite</a>

It's already set in css and there are two states, regular and hover, with hover being shifted by 12px.

a.favorite {
    width: 15px;
    height: 12px;
    background: url(img/icon-fav.png) no-repeat;
    overflow: hidden;
    position: absolute;
    top: 0;
    right: 0;
    text-indent: -300px;
}

a.favorite:hover {
    background-position: 0 -12px
}

When I click the image once, I need the background position to be set the same as the hover state.

I'm doing that like this, and it works:

document.getElementById("favorite_1").style.backgroundPosition = "0 -12px";

But when the link is clicked again, I need it to switch back to the normal background position and I can't get that to work. This is the function I'm trying but it only works for moving the background to "0 -12px", not for moving it back to its original position.

function favoriteBusiness(id){

   if(document.getElementById("favorite_1").style.backgroundPosition == "0 -12px")
    document.getElementById("favorite_1").style.backgroundPosition = "";
   else
    document.getElementById("favorite_1").style.backgroundPosition = "0 -12px";

}

Can someone point me in the right direction here?

Upvotes: 0

Views: 5258

Answers (1)

Diodeus - James MacFarlane
Diodeus - James MacFarlane

Reputation: 114417

Unless you're making calculations, you're better off adding and removing classes that contain the new position. This is usually what's done for manipulating CSS sprites.

Upvotes: 2

Related Questions