- Create thumbnails and dump them all in a “thumbs” folder with the same file names
- OR add something to identify the thumbnails such as: image01-th.jpg, image02-th.jpg etc…
- Place a container that holds the big image and give it an unique ID such as “big-image” OR give the image an unique ID - need a default image
<div id="big-image"><img src="imagename.jpg" alt="" /></div>
OR
<img id="big-image" src="bigimage01.jpg" alt="" />
- Place all of the thumbnails within a container such as: UL, unique ID div, or add a class to each of the thumbnail
<ul id="thumbnails"> <li><img src="image01.jpg" alt="" /></li> <li><img src="image02.jpg" alt="" /></li> <li><img src="image03.jpg" alt="" /></li> </ul>
OR
<div id="thumbnails"> <img src="image01.jpg" alt="" /> <img src="image02.jpg" alt="" /> <img src="image03.jpg" alt="" /></div>OR
<img class="thumbnails" src="image01.jpg" alt="" /> <img class="thumbnails" src="image02.jpg" alt="" /> <img class="thumbnails" src="image03.jpg" alt="" />Note: The last method is more flexible, it doesn’t have to be inside a container meaning the thumbnail can be placed anywhere. Just as long as the bigger image is shown at the exact same place.
- Tell jQuery to find all the thumbnails, and every time the user hovers over each of the thumbnail – replace the “big-image” with the corresponding thumbnail path or file name
To replace the path:
$(document).ready(function(){ $('#thumbnails img').each(function(){ $(this).hover(function(){ var src = $(this).attr('src').replace('thumbs', ''); // take out /thumbs/ before the file name $('#big-image').attr({src: src, title: src, alt: src}); }); }); });
To remove the “_th” identifiers:
$(document).ready(function(){ $('#thumbnails img').each(function(){ $(this).hover(function(){ var src = $(this).attr('src').replace('_th', ''); // take out '-th' $('#big-image').attr({src: src, title: src, alt: src}); }); }); });
To find all the “thumbnails” classes: Simply replace $(‘#thumbnails img’) with $(‘.thumbnails’)
Related Posts
No related posts.
No Responses to “jQuery Journal: Easy jQuery image swap — Step by step”