Reputation: 225
I'm looking to pass the image source of a clicked item into the div of another. For example in the following markup:
<div class="row">
<div id="header">
<img src='placeholder' />
</div>
</div>
<!--row-->
<div class="thumb-wrapper row">
<div class="thumb">
<div class="thumb-content">
<img src="http://static.srcdn.com/slir/w700-h350-q90-c700:350/wp-content/uploads/hulk-mark-ruffalo-marvel-phase-3-movies.jpg" />
</div>
</div>
<div class="thumb">
<div class="thumb-content">
<img src="https://pmcvariety.files.wordpress.com/2015/02/spider-mannew.jpeg?w=670&h=377&crop=1" />
</div>
</div>
</div>
I would like the user to change the image source in the header to whatever image src is within the thumb-content div of the clicked thumb.
I've gotten this to work on a single thumb basis, but I'm not sure how to make it work for many thumbs:
$('.thumb ').on('click', function(e) {
$("#header img").attr("src", "http://placekitten.com/1200/800");
});
Another factor here, the function needs to specifically target the image within the thumb-content div as there may be another image in the thumb div.
Appreciate any direction or help.
Upvotes: 1
Views: 156
Reputation: 240938
Retrieve the src
attribute of the child img
element based on the element that was clicked:
$('.thumb').on('click', function(e) {
var src = $(this).find('.thumb-content img').attr('src');
$("#header img").attr("src", src);
});
You could simplify your code and attach the event listener to the img
elements instead:
$('.thumb img').on('click', function(e) {
$("#header img").attr("src", this.src);
});
Upvotes: 2
Reputation: 3509
Try with:
$('.thumb img').on('click', function(){
$('header img').remove();
$(this).clone().appendTo('header');
});
Upvotes: 0
Reputation: 4216
Here you go:
$("#header img").attr("src", $(this).find('img').attr("src"));
Upvotes: 0
Reputation: 3720
What about something like this, using child selectors?
$('.thumb-content>img').click(function(e) {
console.log('thumb clicked');
$("#header>img").attr("src", $(this).attr("src"));
});
Upvotes: 0