How can I ensure that this transition in CSS

I have an image carousel built using knockout and jquery. For animating slides, I really want to use CSS transitions and NOT jquery aimate. It almost works for me, but I have a problem. In the code below, the "slideRight" part doesn't work, however the else part works fine. It transitions to margin-left 0, although a transition class has been added.

if (slideRight) {
    $(requestedElement).insertBefore(currentElement);
    slideContainer.css('margin-left', -$(self.carousel).width());
    slideContainer.addClass('transition');
    slideContainer.css('margin-left', 0);
} else {
    $(requestedElement).insertAfter(currentElement);
    slideContainer.addClass('transition');
    slideContainer.css('margin-left', -$(self.carousel).width());
}

      

I created a JSFiddle here: http://jsfiddle.net/vnw57nx0/2/

As you will see on the violin, the carousel moves beautifully between slides going from right to left.

But if you find this line in javascript:

self.setIndex(self.currentIndex() + 1);

      

and change it to:

self.setIndex(self.currentIndex() - 1);

      

slides should rotate in reverse order. They do, but they don't liven up. Interestingly, if I debug the script and step through it, it works fine. This made me think it was a timing issue and maybe I need to use a callback function, but jquery.insertBefore..css and .addClass are all synchronous.

Any ideas how I can fix this code that works if I debug, but doesn't if I don't?

+3


source to share


1 answer


The browser doesn't seem to make the transition when you return a style value in the same context. You need to do it in a new context using something like setTimeout

:

if (slideRight) {
    $(requestedElement).insertBefore(currentElement);
    slideContainer.css('margin-left', -$(self.carousel).width());
    setTimeout(function() {
        slideContainer.addClass('transition');
        slideContainer.css('margin-left', 0);
    });
} else {

      



http://jsfiddle.net/vnw57nx0/3/

I found this question because of the Knockout tag, and while you have knockout links in your question, the problem has nothing to do with Knockout. In fact, your code is very anti-knockout since you are using the jQuery selector in your "view model" and using observables where none is needed or even useful.

+3


source







All Articles