Name Mon Lu

Love jQuery/CSS

Blog about Webdev

Twitter supawaza

RSS Twitter Flickr

What I am up to:


Image Swap Example

  1. Cre­ate thumb­nails and dump them all in a “thumbs” folder with the same file names
  2. OR add some­thing to iden­tify the thumb­nails such as: image01-th.jpg, image02-th.jpg etc…
  3. Place a con­tainer 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="" />
  4. Place all of the thumb­nails within a con­tainer 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 flex­i­ble, it doesn’t have to be inside a con­tainer mean­ing the thumb­nail can be placed any­where. Just as long as the big­ger image is shown at the exact same place.

  5. Tell jQuery to find all the thumb­nails, and every time the user hov­ers over each of the thumb­nail – replace the “big-image” with the cor­re­spond­ing thumb­nail 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 “thumb­nails” classes: Sim­ply replace $(‘#thumb­nails img’) with $(‘.thumbnails’)

Share and Enjoy:
  • Digg
  • del.icio.us
  • Facebook
  • email
  • Ping.fm
  • Reddit
  • RSS
  • StumbleUpon
  • Technorati
  • Twitter

Related Posts

No related posts.

This entry was posted on Tuesday, July 21st, 2009 at 3:49 PM and is filed under Web Dev. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

No Responses to “jQuery Journal: Easy jQuery image swap — Step by step”