userlkjsflkdsvm
userlkjsflkdsvm

Reputation: 983

How to replace Image src attr with the one clicked? jQuery

I have one image above four smaller images. When the user clicks one of the smaller images, the smaller image takes the larger images's place. But still remains in it's original spot. I think I'm close to solving it but am in need of help.

HTML

        <div class="col-md-8 modal-images">
         <div class="row large-image">
         <div class="col-md-12">
            <img src="One.png">
             </div>
          </div>
          <br/>
          <div class="row small-image">
              <div class="col-md-4">
                  <img src="One.png">
              </div>
              <div class="col-md-4">
                  <img src="Two.jpg">
              </div>
              <div class="col-md-4">
                  <img src="Three.jpg">  
              </div>
              <div class="col-md-4">
                  <img src="Four.jpg">
              </div>
          </div>
          </div>

JS

$('.small-image img').closest('.col-md-4').click(function(){
        var newimage = ($('.small-image img').closest('.col-md-4').find('img').attr('src'));
       $('.large-image img').attr('src', newimage); 
    });

Upvotes: 0

Views: 38

Answers (2)

prasanth
prasanth

Reputation: 22510

Try with $(this).

$('.small-image img').closest('.col-md-4').click(function(){
        var newimage = ($(this).closest('.col-md-4').find('img').attr('src'));
  console.log(newimage)
       $('.large-image img').attr('src', newimage); 
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-md-8 modal-images">
         <div class="row large-image">
         <div class="col-md-12">
            <img src="One.png">
             </div>
          </div>
          <br/>
          <div class="row small-image">
              <div class="col-md-4">
                  <img src="One.png">
              </div>
              <div class="col-md-4">
                  <img src="Two.jpg">
              </div>
              <div class="col-md-4">
                  <img src="Three.jpg">  
              </div>
              <div class="col-md-4">
                  <img src="Four.jpg">
              </div>
          </div>
          </div>

Alternate way

Its already target with parent .so match with child img

$('.small-image img').closest('.col-md-4').click(function(){
        var newimage = ($(this).children('img').attr('src'));
  console.log(newimage)
       $('.large-image img').attr('src', newimage); 
    });

Upvotes: 2

KaeyangTheG
KaeyangTheG

Reputation: 391

Within the click handler, the 'this' keyword will refer to the .col-md-4 div. So with that in mind the following works:

$('.small-image img').closest('.col-md-4').click(function(){
    var newimage = ($(this).find('img').attr('src'));
   $('.large-image img').attr('src', newimage); 
});

Upvotes: 1

Related Questions