Amanjot
Amanjot

Reputation: 2058

Insert the image sources one after another image

Demo

I want that whenever I click on any image, then that image src should go to image with the img1 id. If the img1 id has already an image, then the image source should go to the image having img2 id and so on.

$( ".img" ).click(function() {
  var newsrc=$( this ).attr("src");
    alert(newsrc);
    $( "#cropimage" ).attr("src",newsrc);
});

The HTML code is here.

<div id="img-container">
    <img id="cropimage" />
</div>
<div>
    <img src="" id="img1" />
    <img src="" id="img2" />
    <img src="" id="img3" />
    <img src="" id="img4" />
    <img src="" id="img5" />
</div>

Upvotes: 0

Views: 1165

Answers (1)

Tushar
Tushar

Reputation: 87203

Add unique id to the container of the blank images.

$("#myImages img[src='']") will select all the images inside #myImages elements those are having src attribute value as blank. first() will get the first from the selected elements.

Demo

$(".img").on('click', function() {
  var newsrc = $(this).attr("src");
  $("#myImages img[src='']").first().attr("src", newsrc);
});
#myImages img {
  display: block;
  clear: both;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<img class="img" src="http://www.w3schools.com/images/w3schools.png" />
<br/>
<img class="img" src="https://www.google.co.in/images/icons/hpcg/ribbon-black_68.png" />
<div id="img-container">
  <img id="cropimage" />
</div>
<div id="myImages">
  <img src="" id="img1" />
  <img src="" id="img2" />
  <img src="" id="img3" />
  <img src="" id="img4" />
  <img src="" id="img5" />
</div>

If you don't want to change your HTML structure, Check this demo

Upvotes: 2

Related Questions