1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

jQuery: How to swap an image

Discussion in 'jQuery' started by enchance, Nov 26, 2008.

  1. #1
    I'm new to jQuery and I'm trying to customize it for an image swapping effect on my site. My problem is that I have 6 images which I want to open in the #view div. How do I assign a thumbnail (I made one for each image) to link to a diff image which will load itself in #view? I named the images img1, img2, img3... for posterity's sake. Do I use each() or something else entirely?

    Here is a sample HTML I made for this

    
    <ul class="list">
    <li><a href="#" class="pic"><img src="img1.jpg" /></a></li>
    <li><a href="#" class="pic"><img src="img2.jpg" /></a></li>
    <li><a href="#" class="pic"><img src="img3.jpg" /></a></li>
    <li><a href="#" class="pic"><img src="img4.jpg" /></a></li>
    <li><a href="#" class="pic"><img src="img5.jpg" /></a></li>
    <li><a href="#" class="pic"><img src="img6.jpg" /></a></li>
    </ul>
    
    Code (markup):
    Help ,anyone?
     
    enchance, Nov 26, 2008 IP
  2. djzmo

    djzmo Active Member

    Messages:
    165
    Likes Received:
    3
    Best Answers:
    0
    Trophy Points:
    58
    #2
    First of all, please add an ID to each images, to make the job easier.
    In this case, I will add the IDs to each images. (just call it: theimage1, theimage2, ...).

    <li><a href="#" class="pic"><img src="img1.jpg" class="theimage1" /></a></li>
    <li><a href="#" class="pic"><img src="img2.jpg" class="theimage2" /></a></li>
    ...
    Code (markup):
    for(var i = 1; i <= 6; i++)
    {
      eval('$("img#theimage' + i + '").hover(function() { $(this).attr("src","img' + i + '-hover.jpg"); }, function() { $(this).attr("src","img' + i + '.jpg"); });');
    }
    Code (markup):
    hover images called img1-hover.jpg, img2-hover.jpg, ... in the code.

    here is the raw code:

    $('yourimg').hover(function()
    {
      $(this).attr("src", "url-to-hover-img");
    }, function() {
      $(this).attr("src", "url-to-default-img");
    });
    Code (markup):
     
    djzmo, Nov 27, 2008 IP
  3. jqueryHowto

    jqueryHowto Guest

    Messages:
    10
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    You can also set href of the links to the images that should be replaced with. Then using jquery read the href and replace the image src with the value of link's href. And of course preventDefault().
     
    jqueryHowto, Apr 13, 2009 IP