Search code examples
javascriptcssdom-eventsbackground-imagesprite

How to implement CSS sprite background into existing JavaScript variable?


I would like to add a sprite image to an existing button which previously used its own image "play.png" which I replaced with "spacer.png" (this item is already set to a fixed soze of 30x35pixels in the css). Goal is to save http requests by combining all such play/pause/ next/previous buttons to go into one singular sprite.png file.

GIVEN, EXISTING CODE:

var $backBtn = $("<img src='" + LIGHTBOX_PATH + "spacer.png' id='back-btn'/>");
$backBtn.css({opacity:BUTTON_OPACITY}).hover(buttonOver, buttonOut);

I ADDED:

#back-btn{
    background: url(http://website.bla/sprite.png) no-repeat -770px -550px) #F00;
    float:left;
}

Why does the sprite image not show up? Even the background is not F00 colored nothing appears there... Only changing the float does have effect meaning that the id does match the #back-btn so its something else... any ideas'?


Solution

  • You should keep your styles in a CSS file except when absolutely necessary (i.e. changing opacity with Javascript). Add a CSS file to your website (or use an existing file if you have one), and add the following declaration:

    #back-btn {
      float: left;
      background: url(http://website.org/sprite.png) no-repeat -770px -550px;
    }