brianrhea
brianrhea

Reputation: 3724

jQuery to change img src based on href

I have four or five thumbnails next to a full-size image. When I click the thumbnail, I just want it to replace the full-size image.

Thumbnail:

<a href="newimage.jpg" class="enlarge"><img src="thumbnail.jpg" alt="thumbnail" /></a>

Fullsize:

<div id="folio-detail">
<img id="fullImage" src="image.jpg" />
</div>

jQuery:

$(function(){
        $("a.enlarge").live('click', function (e) {
            e.preventDefault();
            $("img#fullImage").attr("src", $(this).attr("href"));
         });
    });

This isn't working ... any help?

Upvotes: 3

Views: 8191

Answers (3)

Russ Cam
Russ Cam

Reputation: 125488

A reference to jQuery needs to come before your code so that the jQuery ($) function is defined. I've slightly changed your code too (which was working), but hopefully the change makes it clearer

<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$(function() {
    $("a.enlarge").live('click', function (e) {
       e.preventDefault();
       var href = this.href;
       $("#fullImage").attr("src", href);
    });
});
</script>

An example

Upvotes: 1

Jules
Jules

Reputation: 7223

Your code does work. I have put it into JSFiddle and it works, just have a look here on JSFiddle.

Are you sure you included the JQuery library?

Upvotes: 1

Dough Boy
Dough Boy

Reputation: 39

It looks correct. Have you tried alerting what is happening? I.e. above the e.preventDefault put "alert('here')". Also alert the clicked on href. If both of those are correct, try changing out the full image selector to '#folio-detail img'.

Can you also look at the changing source code (i.e Firebug/Developer tools) to see if anything is changing?

Upvotes: 0

Related Questions