简体   繁体   中英

How to select random divs in a banner rotation

I have managed to create a banner rotation for my website but it rotates 1,2,3,1,2,3.. and so on. I have done some research but cannot seem to find a specific solution to my problem.

The problem is that I would like them to rotate randomly so that the first banner listed is not always the first one that appears because we cannot favour one client over another.

<script type="text/javascript">
  $(window).load(function() {
    startRotator("#rotator");
  })
</script>

<div id="rotator">

<div>
<a href="http://www.website.com" onClick="ga('send', 'event', 'Middle Banner', 'Banner_Click', 'Middle Banner 1 November 2017');" target="_blank">
<img class="mid-banner" src="/images/banners/middle/banner1.jpg" />
</a>
</div> 

<div> 
<a href="http://www.website.net" onClick="ga('send', 'event', 'Middle Banner', 'Banner_Click', 'Middle Banner 2 November 2017');" target="_blank">
<img class="mid-banner" src="/images/banners/middle/banner2.jpg" />
</a>
</div>

<div>
<a href="http://www.website.co.uk" onClick="ga('send', 'event', 'Middle Banner', 'Banner_Click', 'Middle Banner 3 November 2017');" target="_blank">
<img class="mid-banner" src="/images/banners/middle/banner3.jpg" />
</a>
</div>

</div>

<script>
function rotateBanners(elem) {
var active = $(elem+" div.active");
var next = active.next();
if (next.length == 0) 
next = $(elem+" div:first");
active.removeClass("active").fadeOut(200);
next.addClass("active").fadeIn(200);
}

function prepareRotator(elem) {
$(elem+" div").fadeOut(0);
$(elem+" div:first").fadeIn(0).addClass("active");
}

function startRotator(elem) {
prepareRotator(elem);
setInterval("rotateBanners('"+elem+"')", 7000);

}
</script>

Is there any way that I can make them appear in a random order such as 3,1,2,1,3,2... and so on.

Any help would be greatly appreciated!

Thanks, Dave

There are a few ways. Here's what I would do.

First, to make it clear, I would give the slide div sa class:

<div class="slide">

Then in JS:

// Select all slides
var slides = $('div.slide');
// Pick the index of one to show at random (well, pseudo-random)
var showIndex = Math.floor(Math.random() * (slides.length - 1));
// Fade out the active slide
$('.active', slides).fadeOut(200);
// Get the slide to show by its index and fade it in
slides.eq(showIndex).fadeIn(200);

You could also make it a little better by checking if the currently active slide is at the same index as the random number and pick another random number:

var showIndex = -1;
while (showIndex != slides.index('.active')) {
    showIndex = Math.floor(Math.random() * (slides.length - 1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM