jquery display img on different div depending on where it was clicked
Question
To better explain what I need I uploaded an example here.
I have 3 divs, and clicking on either one of them will have the same image menu appear on the right. What I have now is: click on the first div, then go to the menu, choose an image and use .prepend()
to show that image on the clicked div. But if I get the image menu appearing when clicking the second or third div and choose a color, this is still displayed on the first div.
A simplified HTML is something like this:
<div id="tela1"><img src="img/blank.jpg" /></div>
<div id="title_tela1"></div>
<div id="tela2"><img src="img/blank.jpg" /></div>
<div id="title_tela2"></div>
<div id="tela1_options">
<div class="image_carousel1>
Content goes here...
</div>
</div>
<div id="tela2_options">
<div class="image_carousel2>
Content goes here...
</div>
</div>
And the JS:
$('.carousel_image1 img').click(function () {
var imageName = $(this).attr('alt');
var chopped = imageName.split('.');
$('#title_tela1').empty();
$('#title_tela1')
.prepend(chopped[0]);
$img = $(this);
$('#tela1 img').attr('src', $img.attr('src'));
})
I tried using the selector ('#tela1_options .carousel_image1 img')
for each of the three divs, but still when I choose an image is displayed only on the first div.
Can someone take a look and help me figure this out?
Solution
Inside of you click function for the carousel, you have "#tela1" hard coded. That part needs to be dynamic based on what div was clicked. You will probably want to store the clicked div in a variable that will be used inside of the click function. Here is a sample of what your document.ready function could look like:
$(function(){
var clickedDiv = null;
$(".tela").click(function(){
clickedDiv = $(this);
});
$('.carousel_image1 img').click(function () {
var $img = $(this),
imageName = $img.attr('alt'),
chopped = imageName.split('.');
clickedDiv.next().text(chopped[0]);
clickedDiv.find('img').attr('src', $img.attr('src'));
});
});
In order for that to work, you will need to add the class="tela" to the divs.
<div id="tela1" class="tela"><img src="img/blank.jpg" /></div>
<div id="title_tela1"></div>
<div id="tela2" class="tela"><img src="img/blank.jpg" /></div>
<div id="title_tela2"></div>
Here is a working example on jsFiddle: http://jsfiddle.net/jY4qa/2/ I only set up the images in the first carousel to show up. But if you click on one of the blank divs and then an image it sets it correctly. I also had to update the image carousel selector in the JS for my example.