Julix
Julix

Reputation: 627

Redirect to random page (except the current page)

Solved! - didn't update my random number generation after changing from switch statement to array... ups. - Thanks!

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://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"

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://bcitcomp.ca/students/hsloman/Comp1850/final/' + links[randomPage];
// open it
window.open(link,"_self");
};

Resources used sofar

Get current URL in web browser

window.open() should open the link in same tab

Upvotes: 1

Views: 294

Answers (2)

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23389

put this right before the window.open(...) line:

if(link === window.location+"") return pickRandomPage();

This is saying, "if the chosen link is the page we're already on, run the function again" ..so it will keep trying until a new page is given. This is easier than trying to splice the array.

See: recursion for more info.

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150080

but instead I end up getting redirected to "http://bcitcomp.ca/students/hsloman/Comp1850/final/undefined"

The undefined is because your randomPage variable will contain a number between 1 and 3, but the actual valid indices in your links array are only either 0 or 1 because it will only have two elements after you remove the current page URL.

Change:

var randomPage = Math.floor((Math.random() * 3) + 1);

to:

var randomPage = Math.floor(Math.random() * links.length);

Upvotes: 2

Related Questions