Reputation: 3
I am trying to do the following:
What would be the best way to do this?
I tried something like this:
<a href="#" id="changeImage" rel="1"><img class="thumb" src="image1_thumb.jpg" /></a>
<div id="imageBox"> </div>
and the jquery script
<script type="text/javascript">
$(document).ready(function(){
$('#changeImage').click(function(){
var $rel = $(this).find('a').attr('rel');
$("#imageBox").html("<img src='image" + $rel + ".jpg' />");
})
})
</script>
but it's not working.
Thanks for the help!
Upvotes: 0
Views: 7096
Reputation: 27441
Try:
$(document).ready(function(){
$('#changeImage').click(function(){
var rel = $(this).attr('rel');
$("#imageBox").html("<img src='image" + rel + ".jpg' />");
})
});
Also, I'd suggest you have a placeholder image (inside 'imageBox') and just change its 'src' attribute (instead of manipulating the DOM so much for no reason). Something like this:
$("#imageBox img").attr('src', 'image' + rel + '.jpg');
Upvotes: 3
Reputation: 7544
I think what you want is:
<script type="text/javascript">
$(document).ready(function(){
$('#changeImage').click(function(){
var $rel = $(this).attr('rel');
$("#imageBox").html("<img src='image" + $rel + ".jpg' />");
})
})
</script>
Because you clicked on the <a>
, $(this)
is the element with the rel attribute... The .find('a')
was searching for a child element within the link you clicked.
Your code would have worked with this html:
<a href="#" id="changeImage">
<a href="#" rel="1"><img class="thumb" src="image1_thumb.jpg" /></a>
</a>
<div id="imageBox"> </div>
Which is obviously redundant...
Hope that helps :)
Upvotes: 1