Problems with jQuery.before

So, I am building a very simple carousel with 4 divs. It uses 2 jQuery functions to set the div to the first or last position. There are only alpha transitions since I don't need movement.

For some reason, although I can access my divs with .eg (n), etc., the first, last and other various numbers do not work in this function.

code:

$('#prev').click(function() { $('.container .divname').animate({opacity: 0}, 1000,function(){ $('.container .divname:first').before($('.container .divname:last')); $('.container .divname').animate({opacity: 1}, 1000); }); return false; }); 

Therefore, this function does not work.

 $('#prev').click(function() { $('.container .divname').animate({opacity: 0}, 1000,function(){ $('.container .divname:eq(0)').before($('.container .divname:eq(3)')); $('.container .divname').animate({opacity: 1}, 1000); }); return false; }); 

This also does not work, but if I change eq (3) to eq (2) , but obviously one of my divs is missing. I can still access eq (3) because I tested it and made it red.

 $('.container .divname:eq(3)').css({'background-color' : '#ff0000'}); 

It works...

Can anyone tell me why this could happen?

Html example below

 <html> <div class="container"> <div class="divname"> <p>some content</p> </div> <div class="divname"> <p>some content</p> </div> <div class="divname"> <p>some content</p> </div> <div class="divname"> <p>some content</p> </div> </div> </html> 

EDIT:

Now I changed the entire id to a class for w3c children in the audience. The problem still persists.

http://jsfiddle.net/3P8t5/1/

+4
source share
2 answers

The root of your problem is that you put your .before () function to shift the divs into a callback function attached to your four divs - this is called four times, which means everything is shifted four times, returning you back to square one ... and because it is such a simple little loop, it is fast and it seems like nothing happened.

Solution - attach the animation function only to the container;

 $('#prev').click(function() { // Fade just the container - not each placeholder meaning the callback function is only called once, not four times $('.container').animate({ opacity: 0 }, 1000, function() { $('.container .divname:eq(0)').before($('.container .divname:eq(3)')); // Fade back in just the container - not each placeholder $('.container').animate({ opacity: 1 }, 1000); }); return false; });​ 

http://jsfiddle.net/cywjs/1/

+2
source

besides the suggested friends (identifiers must be really unique), I saw in the code.change code "divnaname" to "divname" in the div.eg tags: <div id="divnaname"> ... <div>

Edit:

check out this demo demo

Is this what you are trying to do?

0
source

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


All Articles