Tutorial :JQuery: How to switch image back and forth?



Question:

I have the following HTML:

<div class="listing ref_1">      ...      <div><img src="toggleON.png" /></div>      ...  </div>  <div class="listing ref_2">      ...      <div><img src="toggleON.png" /></div>      ...  </div>    <div class="listing ref_3">      ...      <div><img src="toggleON.png" /></div>      ...  </div>  

What I want to do is programmatically change the toggleON.png image to toggleOFF.png.

I'm trying to use the following code to do so but it's not working:

$('.ref_2').src("toggleOFF.png");  

Anyone know what I'm doing wrong because the code above doesn't work.

Also, is there a better way to handle this?


Solution:1

'.ref_2' points to the div, you'll have to get to the image within the div

$('.ref_2 img').attr("src","toggleOFF.png");  

would probably do it for you.


Solution:2

You need to select the img tag in side .ref_2

$('.ref_2 img').attr("src","toggleOFF.png");  

It might be better though to put the image definition in css and swap classes.

<style>  .toggleOn div{     background: url('toggleOn.png') no-repeat;  }  .toggleOff div{     background: url('toggleOff.png') no-repeat;  }  </script>    <div class="listing ref_1 toggleOn">      ...      <div></div>      ...  </div>  <div class="listing ref_2 toggleOn">      ...      <div></div>      ...  </div>    <div class="listing ref_3 toggleOn">      ...      <div></div>      ...  </div>    <script>  $('.ref_2').removeClass('toggleOn').addClass('toggleOff');  </script>  

This makes it really easy to change the image and lets you use the class as a state toggle if you need to check on it later.

Also it looks like you are using ref_# as a unique identifier, if so then it would be better to make it the ID of the div, will speed up jQuery's ability to find the element.


Solution:3

What I like to do is put both images in my main document in a hidden div, like:

<div style="position: absolute; visibility: hidden">    <img id="toggleON" src="/whatever/toggleON.png" .../>    <img id="toggleOFF" src="/whatever/toggleOff.png" .../>  </div>  

That way they're both in the browser's cache. Then, to toggle an image from one to the other, you can do something like:

$(".whatever img").replaceWith($("#toggleON").clone());  


Solution:4

Another solution is to put both image on absolute position, with the default one is set to the front (Using z-index property).

On mouse hover, you can hide the one in the front and the toggled-off image will showed up. The advantage of using this method is you could actually use animation technique to make it even smoother. It's what I did here. (It would be better if you have an additional wrapper div and set the mouse hover event on it)


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »