Markcce Eros Markcce Eros - 1 month ago 10
Javascript Question

Javascript onclick function pass img src

I have 3 images which each have an

onclick
and a parameter passed. Here's the HTML:

<div class="row">
<div class="col-md-12 thumb">
<div class="thumbnail" onclick="myfunction(1);"><img class="img-responsive" src="assets/placeholders/sliders/slider1.png" alt="" /></div>
</div>
</div>
<div class="row">
<div class="col-md-12 thumb">
<div class="thumbnail" onclick="myfunction(2);"><img class="img-responsive" src="assets/placeholders/sliders/slider2.png" alt="" /></div>
</div>
</div>
<div class="row">
<div class="col-md-12 thumb">
<div class="thumbnail" onclick="myfunction(3);"><img class="img-responsive" src="assets/placeholders/sliders/slider3.png" alt="" /></div>
</div>
</div>


What I need to do is have a function which gets the
img
src
value of the
myfunction
passed parameter. So for example:

myFunction(id) {
$('body').html(/* passed parameter's img src here */);
}


How can I do this?

Answer

You can pass this as a parameter to the function which will be a reference to the clicked div element. You can then get the child img and read the src attribute.

However a much better solution would be to use unobtrusive event handlers over outdated on* event attributes. Try this:

$('.thumbnail').click(function() {
  var $thumb = $(this);
  console.log($thumb.data('foo'));
  console.log($thumb.find('img').attr('src'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="col-md-12 thumb">
    <div class="thumbnail" data-foo="1">
      <img class="img-responsive" src="assets/placeholders/sliders/slider1.png" alt="" />
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-12 thumb">
    <div class="thumbnail" data-foo="2">
      <img class="img-responsive" src="assets/placeholders/sliders/slider2.png" alt="" />
    </div>
  </div>
</div>
<div class="row">
  <div class="col-md-12 thumb">
    <div class="thumbnail" data-foo="3">
      <img class="img-responsive" src="assets/placeholders/sliders/slider3.png" alt="" />
    </div>
  </div>
</div>