Using jQuery to reorder items

Does anyone know what I'm doing wrong? I'm trying to change the display order of some images, I want the images to change right / left by one place every time I clicked the button. This is what I tried but no luck.

Any help or understanding will be truly appreciated.

$("#rightShift").click(function(){ $("img").hide(); var count = $("img").size(); $("img").each(function(i) { var indexImg = count - i; $("img:eq(indexImg)").show(); }); }); $("#leftShift").click(function(){ $("img").hide(); $("img:last").prependTo("img"); $("img").show(); }); 
+4
source share
3 answers

Assuming you want this to work like a carousel that goes around (the last image becomes the first when you move to the right), here's how I do it:

 $("#rightShift").click(function(){ $("img:last").detach().insertBefore("img:first"); }); $("#leftShift").click(function(){ $("img:first").detach().insertAfter("img:last"); }); 
+16
source

You are trying to access a variable inside a string. This makes no sense.
Did you really mean:

 $("img:eq(" + indexImg + ")").show(); 

But a more efficient implementation:

 $(this).prev().show(); 

The most effective implementation without side effects:

 $("#rightShift").click(function(){ var $images = $("img"); // <-- Reference to all images $images.hide(); //var count = $images.length; //<-- Unused variable, delete it? $images.each(function(i) { $(this).prev().show(); }); }); $("#leftShift").click(function() { var $images = $("img"); $images.hide(); $images.last().prependTo("img"); // OR: $images.before($images.last()); $images.show(); }); 
+4
source

It:

 $("img:eq(indexImg)").show(); 

Must be:

 $("img:eq(" + indexImg + ")").show(); 

Not sure if other things are wrong.

+1
source

Source: https://habr.com/ru/post/1395967/


All Articles