apielotje apielotje - 4 months ago 12
jQuery Question

jQuery slider help needed

I made a slider, but i'm not that great with jQuery. I would like to pause the slider on hover, and also would like to prevent the buttons from being used when an animation is playing. Can anybody help me with this?

var jq = $.noConflict();

setInterval(function() {
var leftPos = jq('#browser').scrollLeft();
if(leftPos == 5400){
jq('#browser').animate({scrollLeft: 0}, 800);
}else{
jq('#browser').animate({scrollLeft: leftPos + 900}, 800);
}
}, 3000);

jq('.rightarrow').click(function() {
var leftPos = jq('#browser').scrollLeft();
if(leftPos == 5400){
jq('#browser').animate({scrollLeft: 0}, 800);
}else{
jq('#browser').animate({scrollLeft: leftPos + 900}, 800);
}
});

jq('.leftarrow').click(function() {
var leftPos = jq('#browser').scrollLeft();
if(leftPos == 0){
jq('#browser').animate({scrollLeft: 5400}, 800);
}else{
jq('#browser').animate({scrollLeft: leftPos - 900}, 800);
}
});


This is my fiddle:

https://jsfiddle.net/apielotje/2kyaJ/958/

Answer

Updated: fixed bug on arrows.

Demo

Is this what you want? I just hid the buttons when the animation is played, and when a hover is detected they are shown again. If you want the buttons can just be disabled instead of hidden.

var jq = $.noConflict();

var siId = -1,
    si = function () {
        //hidding buttons
        siId = setInterval(function () {
            var leftPos = jq('#browser').scrollLeft();
            if (leftPos == 5400) {
                jq('#browser').animate({
                    scrollLeft: 0
                }, 800);
            } else {
                jq('#browser').animate({
                    scrollLeft: leftPos + 900
                }, 800);
            }
        }, 3000);
    }

//hidding arrows initially
jq('.rightarrow, .leftarrow').hide();

jq('#scrolldiv_container').mouseenter(function(){
    jq('.rightarrow, .leftarrow').show('fast');
    clearInterval(siId);
})
jq('#scrolldiv_container').mouseleave(function(){
    jq('.rightarrow, .leftarrow').hide('fast');
        si();
});

jq('.rightarrow').click(function () {
    var leftPos = jq('#browser').scrollLeft();
    if (leftPos == 5400) {
        jq('#browser').animate({
            scrollLeft: 0
        }, 800);
    } else {
        jq('#browser').animate({
            scrollLeft: leftPos + 900
        }, 800);
    }
});

jq('.leftarrow').click(function () {
    var leftPos = jq('#browser').scrollLeft();
    if (leftPos == 0) {
        jq('#browser').animate({
            scrollLeft: 5400
        }, 800);
    } else {
        jq('#browser').animate({
            scrollLeft: leftPos - 900
        }, 800);
    }
});

//starting slider here
si();
Comments