Julix Julix - 10 months ago 50
Javascript Question

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!


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 "

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


var pickRandomPage = function () {
// random Pages available
var links = [

// 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){

// 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

Resources used sofar

Get current URL in web browser

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

Answer Source

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.


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


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