0

I have a enlarge image from thumb to large by ajax using click.

they using the same html elements just replace the img src for example:

src="image_thumb.jpg"

switch to

src="image_large.jpg"

My question is, how to switch back to the thumb image when the user clicks again.

vzhen
  • 11,137
  • 13
  • 56
  • 87

2 Answers2

1

You can use the toggle-event API to use two functions: one to change from thumb to large, the other to change from large to thumb. By using toggle, it will alternate between the two each time the user clicks.

If you want to try the class method, you can do this:

$('img').on('click', function(){
   if ($(this).hasClass('thumb')){
     $(this).removeClass('thumb').addClass('large');
     //set your large image here
   } else {
     $(this).removeClass('large').addClass('thumb');
     //set your thumb image here
   }
});

The bonus here is that you can use CSS to make any changes to accommodate the large image or thumbnail.

mgoffin
  • 755
  • 6
  • 12
  • Toggle is the way to go. In the first callback, get the image using AJAX, and in the second, replace it with the thumb's src. – Rutwick Gangurde Jan 20 '13 at 16:49
  • I just check out the .toggle() and it says deprecated in 1.8 and will be removed in 1.9. Any replacement for .toggle() ? – vzhen Jan 20 '13 at 16:54
  • Looks like there's nothing: [see this post](http://stackoverflow.com/questions/14338078/equivalent-of-deprecated-jquery-toggle-event) – mgoffin Jan 20 '13 at 17:00
  • just check it in click event – pocesar Jan 20 '13 at 17:07
  • yea, the other option would be to [add a class](http://api.jquery.com/addClass/) to the img tag like "thumb", and when you change it to the large image, [remove](http://api.jquery.com/removeClass/) the thumb class and add another class like "large". Then you can just check if it [has a class](http://api.jquery.com/hasClass/) and change it accordingly. – mgoffin Jan 20 '13 at 17:10
1

Since toggle is deprecated in 1.8 and removed in 1.9, you should do this

$('img').on('click', function(){
  var $this = $(this);
  if ($this.data('originalSrc')){
    $this.prop('src', $this.data('originalSrc'));
    $.removeData(this, 'originalSrc');
  } else {
    $this.data('originalSrc', $this.attr('src'));
    $this.prop('src', 'image_large.jpg');
  }
});

DEMO http://jsfiddle.net/PSFeJ/

pocesar
  • 6,860
  • 6
  • 56
  • 88
  • This works, but can you explain $(this) and var $this = $(this) ? – vzhen Jan 20 '13 at 17:38
  • inside the event callback, `this` refers to the DOM element. so, you want to "jqueryfy" your DOM element to manipulate it, that's the reason for `$this`. even though jQuery caches multiple calls to the same DOM element, it's of good practice to always assign your jquery object with a set of elements to a variable if you are going to perform multiple operations on it – pocesar Jan 20 '13 at 18:00
  • I always using for example $('img'). Thanks for explaination. – vzhen Jan 20 '13 at 18:08