Reputation: 81
So basicly what I want to make is everytime you click on an image outside of the div "img-container" it changes the src path in "img-container" div. Came this far, now I don't know how to finish this code.
Thanks in advance
<div class="img-container">
<img id="changeMe" src="">
</div>
<img src="images/preview-1.jpg">
<img src="images/preview-2.jpg">
<img src="images/preview-2.jpg">
$('img').click(function(event) {
alert($(this).attr('src'));
});
Upvotes: 3
Views: 9395
Reputation: 763
no need to change the markup just change script as follow
$('img:not(div img)').click(function(event) {
$(".img-container img").attr('src',$(this).attr('src'));
});
Upvotes: 2
Reputation: 1304
Adneneos' answer is the most efficient.
However, this method would be good if, for some reason, you can't add classes to the images. This uses the .each() method...
$(document).ready(function() {
$("img[id!='changeMe']").each(function() {
$(this).click(function() {
$("#changeMe").attr('src', this.src);
});
});
});
EDIT: You would need to define a more specific of sorts, because this method would check every image on the page. This answer is based on the code provided. However, adeneos answer may be easier.
Upvotes: 0
Reputation: 318332
Give them a class
<div class="img-container">
<img id="changeMe" src="">
</div>
<img class="preview" src="images/preview-1.jpg">
<img class="preview" src="images/preview-2.jpg">
<img class="preview" src="images/preview-2.jpg">
Then do
$('.preview').on('click', function() {
$('#changeMe').prop('src', this.src);
});
Upvotes: 8