Understanding Simple Carousel Navigation Code

I'm new to jQuery in general and have basically done this one slide transition, it has minimal and compact code:

$(function () {
    var str_next = $('.cara .item').eq(1);

    function slide(elem) {
        elem.addClass('next');

        $('.cara .item').each(function() {
            if ($(this).hasClass('active')) {
                console.log('does have it');
                $(this).removeClass('active');
            }
        });

        setTimeout(function () {
            elem.removeClass('next').addClass('active');
        }, 2000);
    }

    slide(str_next);
});

      

The spell is here

If you look closely at jQuery, the following lines of code cause one slide transition effect:

setTimeout(function(){
    elem.removeClass('next').addClass('active');
}, 2000);

      

Now it is very important for the transition effect that the class is next

bound to elem

, but in the above code the class next

is removed from elem

and there is still a transition, why ?

For example, if I were to change the above lines of code like this:

setTimeout(function(){
    elem.removeClass('next');
    setTimeout(function() {
        elem.addClass('active');
    }, 500);
}, 2000);

      

There will be no transition, as it happened below:

setTimeout(function(){
    elem.removeClass('next').addClass('active');
}, 2000);

      

Why is it due to the deletion of the class next

, the transition is happening?

+3


source to share


1 answer


The transition does not play as it depends on the position of the image.

Before the image slides into view, its display property is set to none, making it invisible and unchanged.

By adding the following class, the position of the element is set to the left: 100%, this causes it to move to the right, effectively out of view.

When you remove the next class and add the active class, the image's display property is set to lock, making it visible and removing the next class, the image is returned to its original position (where you can see it after the animation).



Now if you remove the next class first, the image will move to its original position while being invisible, so there is no animation.

So, to answer your question, the following class provides a starting position for a tween, if the image is not at that starting position, it doesn't need to move and so there is no animation.

Edit clarification: The transition always plays in the background, only because an active class is added it becomes visible. Therefore, even if you remove the next class before adding the active class, the transition starts playing and becomes visible. The transition is due to differences in the position of the following classes, the visibility of the images comes from the active class, they are completely separated. So the transition is always rendered when the next class is removed, it just isn't always rendered.

+1


source







All Articles