user298519 user298519 - 7 months ago 12
Javascript Question

JQuery: How to trigger certain events depending on what is clicked?

So I have a row of images displayed and I want to display a different list item when each picture is clicked. Here's a demo of what I have so far.

https://jsfiddle.net/OneCodeMan/3975prLy/1/

$("img:nth-child(1)").on('click', function() {
$("#listitem1").text(lines[0]);
});

$("img:nth-child(2)").on('click', function() {
$("#listitem2").text(lines[1]);
});


But that's for eight images.. so this is too much code to do all that.
I tried making a for loop too.

for(var i=0; i < lines.length; i++) {
$('img.nth-child(' + parseInt(i+1) +')').on('click', function() {
$("#listitem"+ i+1).text(lines[i]);
})
}


But I got this error:
Uncaught Error: Syntax error, unrecognized expression: img.nth-child(1)

How do I fix this?

Answer

You can accomplish it with .index(), and .eq() so:

$("#shots img").on('click', function() {
  var idx=$(this).index();
  $("#alcoholpoem li").eq(idx).text(lines[idx]);
}); 

Check the below snippet

var lines = ['Eight shots later,',
  'I still remember your name.',
  'I never drank alcohol,',
  'For the taste',
  'This is text',
  'This is text',
  'This is text',
  'This is text'
];

$("#shots img").on('click', function() {
  var idx = $(this).index();
  $("#alcoholpoem li").eq(idx).text(lines[idx]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="shots">

  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>
  <img src="http://i.ebayimg.com/00/s/NzUxWDY0MA==/z/PRoAAMXQNbxRfYfj/$T2eC16VHJH!FFmOoS6i!BRfYfi6Vl!~~60_12.JPG?set_id=880000500F" width=100 height=100>

</div>

<ul id="alcoholpoem">
  <li id="listitem1"></li>
  <li id="listitem2"></li>
  <li id="listitem3"></li>
  <li id="listitem4"></li>
  <li id="listitem5"></li>
  <li id="listitem6"></li>
  <li id="listitem7"></li>
  <li id="listitem8"></li>
</ul>

Comments