1

I am using a random function to randomly slide between 4 swiper sliders, here is my code :

var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
    var rand = Math.floor(Math.random() * 4);
    swipers[rand].slideNext();
    }, 3000);
}

How should i proceed if i wanted to randomize between slideNext() and slidePrev() ? I tried many things like this :

var direction = ['slideNext()', 'slidePrev()'];
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
   var randx = Math.floor(Math.random() * 4);
   var randy = Math.floor(Math.random() * 2);
   swipers[randx].direction[randy];
}, 3000);

But it's not working, probably for obvious reasons, but please help me understand why it's not working. And how i could possibly achieve that?

2 Answers 2

2

Just put the method name in the arrays, without parentheses. Then use it to index the object, and call the result of that.

You should also use <arrayname>.length rather than hard-coding the lengths when you get the random index, so you don't have to change it if you add more swipers or directions.

var direction = ['slideNext', 'slidePrev'];
var swipers = [swiper1, swiper2, swiper3, swiper4];
setInterval(function(){
   var randx = Math.floor(Math.random() * swipers.length);
   var randy = Math.floor(Math.random() * direction.length);
   swipers[randx][direction[randy]]();
}, 3000);
Sign up to request clarification or add additional context in comments.

Comments

1

You're pretty close! Just change how you're setting the direction and I think you got it:

swipers[randx][direction[randy]]();

Also remove the parenthesis from your array and just leave the function names there.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.