views:

319

answers:

3

Hello guys,

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');
 }
 );

Thanks for any info.

+9  A: 

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");
});
RSolberg
Damn that was fast.
womp
Yeah, speedy! Btw, you can just use toggle by itself, no need for the click too: http://docs.jquery.com/Events/toggle
brianng
Excellent solutions guys, many thanks !
Peanuts
+3  A: 

Do it with classes. It's much much easier.

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

<script type="text/javascript">
$(function() {
  $("#spite").click(function() {
    $(this).toggleClass("moved");
  });
});
</script>
cletus
+3  A: 

You're mis-understanding the concept of a callback. A callback in programming is a function that gets called immediately after the executing code.

In your case, you're saying the following:

On click, set my background position to -40px. Once you're done with that, set it to 40px (immediately undoing what your function just did).

In this case, you don't need to use a callback function. You need to set up a toggle so that when the user clicks on your element, one function is run...then the next time they click on that element, the second function is run.

Justin Niessner