jquerycsstogglebackground-position

changing an element's background using the CSS property


I have a div with a background, and I'd like to change the background's position on click.

This is my jQuery snippet :

$('#sprite').click(function () {
    $(this).css('backgroundPosition', '-40px');
});

While this is working ok, I'd like to return to the original position with a 'second' click, resetting all.

Mmm, is this what's called a 'callback' right?

I tried so with that but it didn't work :

$('#sprite').click(function () {
    $(this).css('backgroundPosition', '-40px');
},function () {
    $(this).css('backgroundPosition', '40px');
});

Solution

  • You should consider using a "toggle" function for this... It'll allow you to go between 2 different CSS classes... Check out this tutorial here.

    $('#sprite').click(function() {
       $(this).toggle(
          function(){
        $(this).css('backgroundPosition', '40px');
          }, 
          function () {
        $(this).css('backgroundPosition', '-40px');
        });
    });
    

    Another option rather than setting the CSS property directly would be to create a CSS class for your background and simply toggle that class.

    CSS

    <style type="text/css">
        .spritebg { background-position: -40px; }
    </style>
    

    jQuery

    $("#spite").click(function() {
       $(this).toggleClass("spritebg");
    });