0

How can I swap two images back and forth, like for toggle.

Tried this but only works with the first try, does not switch the image back

$("img.trigger2").click(function(){
        $(this).toggleClass("active").next().slideToggle("slow");
        this.src = this.src.replace("collapse.gif","expand.png");
        this.src = this.src.replace("expand.png","collapse.gif");

 });
nunopolonia
  • 14,157
  • 3
  • 26
  • 29
Jason
  • 21
  • 1
  • 2

4 Answers4

5

How about you have 2 separate images and toggle visibility instead, so you don't have to keep reloading the image?

Why don't you set the src attribute instead of using a .src.replace? In jQuery, this is it:-

$("img.trigger2").click(function() {
   if (this.src == 'expand.png')
      this.src = 'collapse.gif';
   else
      this.src = 'expand.png';
});
Reigel Gallarde
  • 64,198
  • 21
  • 121
  • 139
evandrix
  • 6,041
  • 4
  • 27
  • 38
  • 1
    faster and better is to use `this.src` instead of `$(this).attr('src')` – Reigel Gallarde Jan 28 '11 at 02:54
  • If you are going to have two img tags, then you can do it with css only :) You can
    and #div.normal:hover img.hover { /* toggle visibility here */ } ... maybe this solution deserves another answer.
    – ludesign Jan 28 '11 at 02:56
2

If it is like a button, then use CSS background-image and set a class like "active" on click. Just toggle the className.

lepe
  • 24,677
  • 9
  • 99
  • 108
0

best to load both images beforehand and just make visible and invisible when swapping

Kris Ivanov
  • 10,476
  • 1
  • 24
  • 35
0

You can do it in many ways, I can think of at least 6 different ways but I am giving you only one of them as an example:

- javascript code

$(document).ready(function() {
    // attaching onclick event listener to all images with class swappable
    $('img.swappable').click(function() {
        // get current event target
        var $this = $(this);

        // get current src value and store it in swap variable (local scope)
        var swap = $this.attr('src');
        // set src's new value to the value of rel=""
        $this.attr('src', $this.attr('rel'));
        // set rel's value to the old src value
        $this.attr('rel', swap);
    });
});

- html code

<img src="your/non_hover/image/address" rel="your/hover/image/address" class="swappable" />

Note: The code is well formatted for readability but can be optimized for fewer calls and minified.

ludesign
  • 1,353
  • 7
  • 12