lundi 24 octobre 2016

Redirect to random page (except the current page)

Problem

Building a web comic and wanted to have one of those "random" buttons, where you jump to any of the strips. I'm assuming the best way to do this would be something on the back end (PHP or such), but I want to do it with JavaScript.

I got as far as picking a random page, but had the problem that it would sometimes redirect to the page it's already on (or rather often until I have more pages). I tried to make it take the page out of the array if the current page is the same as the target page, but instead I end up getting redirected to "http://ift.tt/2eLY5Lq"

I even made sure to use splice instead of delete. Doesn't that re-index the list?


Code

var pickRandomPage = function () {
// random Pages available
var links = [
    "construction.html",
    "placeholder.html",
    "noplaymobil.html"];

// current Page
var currentURL = window.location.href;
var currentPage = currentURL.substr(currentURL.lastIndexOf('/')+1);

// get rid of current page from array of options
for(var i = 0; i < links.length; i++){
  if(links[i] == currentPage){
    links.splice(i,1);
  }
}

// get a random number, rounded number between 0 and number of links
var randomPage = Math.floor((Math.random() * 3) + 1);
var link = 'http://ift.tt/2dQYluS' + links[randomPage];
// open it
window.open(link,"_self");
};




Aucun commentaire:

Enregistrer un commentaire