starbucks
starbucks

Reputation: 3016

How can I swap an image on click and show it onclick or when clicked elsewhere?

My HTML structure is:

   <div class="box_container">
      <a class="box_one entire_sprite_image" href="#"></a>
      <a class="box_two entire_sprite_image" href="#"></a>
    </div>

Onclick of box_one or box_two I want them to go to an active state. I intend to use JQuery to do that. So when box_one or box_two is clicked the image color changes to reflect active state.

I am not sure how I can use JQuery to do this because instead of having two different images for each box I am using a sprite image.

I am new to Jquery but got up to this point:

(function ($) {
      $(document).ready(function() {
      $(".box_one, .box_two").click(function () {

      });
  });
    })(jQuery);

How can I still use Jquery to change the image when clicked and change back to original when clicked on that image again and when something else is clicked?

Upvotes: 1

Views: 206

Answers (2)

Sushanth --
Sushanth --

Reputation: 55750

use classes for the swap

    .box_one{
         background : 'imgUrlOne'
    }

    .box_one.swap{
         background : 'imgUrlOneSwap'
    }

    .box_two{
         background : 'imgUrlTwo'
    }

    .box_two.swap{
         background : 'imgUrlTwoSwap'
    }

<div class="box_container">
      <a class="box_one entire_sprite_image" href="#"></a>
      <a class="box_two entire_sprite_image" href="#"></a>
</div>

Javascript

(function ($) {
      $(document).ready(function() {
      $(".box_one, .box_two").click(function () {
            $(this).hasClass('swap') ? $(this).removeClass('swap')  
                                     : $(this).addClass('swap')
      });
});(jQuery);

Updated Check Fiddle

Upvotes: 1

Stone
Stone

Reputation: 2668

My assumption is that your asking how to change the sprite on the element that was clicked. To do that you'd adjust the background-position of the clicked element as shown here:

$(document).ready(function(){
    $(".box_one, .box_two").click(function () {
        $(this).css('backgroundPosition', '0 -54px'); // replace values with appropriate sprite values
    });
});

Please clarify if you're use case is different from this.

UPDATE: use an active class and toggle it. toggle active class by clicking on other elements.

<div class="box_container">
      <a class="box_one active" href="#"></a>
      <a class="box_two" href="#"></a>
</div>

$(document).ready(function(){ 
    $(".box_one").click(function () { 
        $(this).toggleClass('active');
    }); 

    $(my_selected_elements).not(".box_one").click(function () { 
        $(this).toggleClass('active');
    }); 
}); 

Upvotes: 1

Related Questions