JordanBarber JordanBarber - 1 month ago 8
HTML Question

Prepend last slide to beginning of slider before sliding

I have the following javascript object controlling my slider:

Slider = {
slideWrap: "#slider ul",
slide: "#slider ul li",
prevTrigger: "#slider a.prev",
nextTrigger: "#slider a.next",
control: "#slider a.control",
init: function() {
jQuery(this.nextTrigger).click(this.moveRight.bind(this));
jQuery(this.prevTrigger).click(this.moveLeft.bind(this));
},
moveRight: function(e) {
e.preventDefault();
jQuery(this.slideWrap).removeClass("no-transition");
jQuery(this.slide).first().clone().appendTo(this.slideWrap);
jQuery(this.slideWrap).css("marginLeft", "-100vw");
jQuery(this.control).css("pointer-events", "none");
setTimeout(function(){
jQuery("#slider ul").addClass("no-transition");
jQuery("#slider ul li").first().remove();
jQuery("#slider ul").css("marginLeft", "0px");
jQuery("a.control").css("pointer-events", "auto");
}, 500);
},
moveLeft: function(e) {
e.preventDefault();
jQuery(this.slideWrap).removeClass("no-transition");
jQuery(this.slide).last().clone().prependTo(this.slideWrap);
jQuery(this.slideWrap).css("marginLeft", "100vw");
setTimeout(function(){
jQuery('#slider ul').addClass('no-transition');
jQuery('#slider ul li').last().remove();
jQuery('#slider ul').css("marginLeft", "0px");
jQuery('a.control').css('pointer-events', 'auto');
}, 500);
}
}


Moving to the right works great as the slider slides to the right, clones the first slide, appends it to the end of the slider and then removes the original first slide in the timeout function. However, I have an issue with sliding left as the last slide needs to be prepending before the slider moves.

See my fiddle here...https://jsfiddle.net/f2hb68tn/12/

Answer

You can try this jsfiddle: https://jsfiddle.net/f2hb68tn/21/.

Here is the modified code:

moveLeft: function(e) {
    e.preventDefault();
    jQuery(this.slideWrap).addClass('no-transition');
    jQuery(this.slide).last().clone().prependTo(this.slideWrap);  // Prepend last slide
    var widthInPixels = "-" + jQuery("#slider").width() + "px";   // In pixels for IE11 
    jQuery(this.slideWrap).css("marginLeft", widthInPixels);   // Stay on current slide
    jQuery(this.control).css("pointer-events", "none");
    setTimeout(function () {
        jQuery('#slider ul').removeClass("no-transition");
        jQuery('#slider ul').css("marginLeft", "0px");     // Transition to first slide
     }, 10);                                   // Zero ms does not work well in Firefox
    setTimeout(function(){
        jQuery('#slider ul').addClass('no-transition');
        jQuery('#slider ul li').last().remove();                   // Remove last slide
        jQuery('a.control').css('pointer-events', 'auto');
    }, 500);
}

In IE11 (and maybe other versions of IE), widthInPixels must be given in pixels (e.g. "-524px"). If you don't need to support that browser, you can use "-100vw" instead.

Comments