Such a dilemma. Made a slider, everything works well except for one thing: if you click on one picture 2 times, then the big version disappears completely. I assume that prepend () does not work.

$('.laast img').each(function(){ var oldImg = $(this).attr('src'); var ext= /(\.\w{3,4}$)/; var newImg = oldImg.replace(ext,'_q$1'); var newI= $('<img src="'+newImg+'">'); $(this).click(function(){ newI.hide(); $('.big').prepend(newI); newI.fadeIn(1000); $('.big img:last').fadeOut(1000,function(){ $(this).remove(); }); }); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="laast"> <p>Заголовок заголовок</p> <img src="image/small/blue.jpg" alt=""> <img src="image/small/green.jpg" alt=""> <img src="image/small/orange.jpg" alt=""> <img src="image/small/purple.jpg" alt=""> <img src="image/small/red.jpg" alt=""> <img src="image/small/slide1.jpg" alt=""> <div class="big"> <img src="image/small/blue_q.jpg" alt="" class="q2"> </div> </div> 

  • You do not need a cycle. Rewrite code using $('.laast > img').click(function() { ... }); - Igor
  • Cycle to pre-load the path for the cache so that it does not hang - PeGaS
  • "one picture 2 times the big version disappears" - because newI and $('.big img:last') correspond to the same DOM element. - Igor
  • @Igor But when prepend () is triggered, it is no longer ".big img: last" there should be 2 elements there - PeGaS
  • see the answer below. - Igor

1 answer 1

prepend , of course, works.

"one picture 2 times the big version disappears" - because newI and $('.big img:last') correspond to the same DOM element. That is, the new DOM element is not added, it already exists inside the jQuery wrapper, and your code adds it to its own parent.

 if (newI[0] != $('.big img:last')[0]) { $('.big img:last').fadeOut(1000,function(){ $(this).remove(); }); } 

or

 $('.big img:last').not(newI).fadeOut(1000,function(){ $(this).remove(); }); 
  • Yes thank you. I will use a conditional statement. It helped - PeGaS
  • But I did not use the cycle for nothing? so that the path to load in advance for the picture and nothing freezes - PeGaS