Reputation: 23
Alright I have a div that contains an image,
<div id="image">
<img src="images/medium/1.png" />
</div>
Now I want to change the src into images/medium/2.png when I click on a link with jQuery.
I have searched but couldn't find it that's why i'm asking here. I am a beginner with jQuery so I would appreciate it if you explain everything very well.
Upvotes: 2
Views: 12380
Reputation: 6547
$('a.imageChanger').click(function()
{
$('#image img').attr('src','newImage.png');
}
This will probably do the trick, but I'm not sure if this is a nice way of doing it, because the texture has to be loaded again. Most of the time, you'll switch between two images that are already in your div. Set one to visible and one to hidden on the click method.
Example
<a href="somelink" class="imageChanger">Click here</a>
<div id="image">
<img class="currentImage">
<img class="hiddenImage">
</div>
The javascript:
// toggle both classes that display or hide an image.
$('a.imageChanger').click(function()
{
$('#image img')each(function()
{
$(this).toggleClass('currentImage');
$(this).toggleClass('hiddenImage');
});
});
This script only works with 2 images, not with 3 or more. But there are a lot of rotator plugins already available.
And the css:
.hiddenImage
{
display:none;
}
.currentImage
{
}
I didn't test this code, but it will look like something like this. It is just a concept.
Upvotes: 6
Reputation: 165971
$("#image img").attr("src", "images/medium/2.png")
should do the trick. It selects the img
element within the element with id
"image", then changes the src
attribute.
You can run this in the click
event handler of your link like so:
$("#linkId").click(function() {
$("#image img").attr("src", "images/medium/2.png");
});
Upvotes: 1
Reputation: 227270
$('#image').click(function(){ // Or whatever element you want to click on
$('img', '#image').attr('src', 'images/medium/2.png'); // Change the src
});
Upvotes: 0
Reputation: 78650
$("LINK SELECTOR GOES HERE").click(function(){
$("#image img").attr("src","images/medium/2.png");
});
But if you really only intend to do this once, you may want to use
Upvotes: 2