0

I'm trying to create a previous button that will cycle through an array of urls. I got it to work as intended, however I had to use .indexOf() when checking if the current url is greater than the first item in the array. Since the urls will most likely be changing, I don't want to specify the exact url.

Here is the working example:

var pageList = ["january_28-2016.html", "february_06-2016.html", "march_17-2016.html"]
var url = window.location.pathname; 
var page = url.substring(url.lastIndexOf('/')+1); 
var currentPosition = pageList.indexOf(page); 

document.getElementById('prev-btn').onclick = function(){
    if(currentPosition>pageList.indexOf("january_28-2016.html")) {window.location = pageList[--currentPosition];}
    else {window.location = pageList[pageList.length-1];}
}

I tried

 if(currentPosition>pageList[0])

and

var page1 = pageList[0]
if(currentPosition>page1)

but could not get it to function. Is there a better way of accomplishing this without using pageList.indexOf("january_28-2016.html")) to get the first element?

Hysteresis
  • 77
  • 8
  • 1
    In javascript you can find elements in arrays by its description too.. Like: pagelist["january_28-2016.html"] – Rafael A. M. S. Aug 05 '16 at 15:34
  • Are you sure the `pageList` array holds the full URL? It seems it's only the last part. Also the `Array.prototype.rotate()` (http://stackoverflow.com/a/38010679/4543207) might turn out to be useful for your application. – Redu Aug 05 '16 at 15:53
  • Thanks for the information. I'll take a look at the Array.prototype.rotate() solution as well. – Hysteresis Aug 05 '16 at 16:13

1 Answers1

1

You can verify the index > 0.

if(currentPosition>0)
  • Yup, well that totally worked. I feel like an idiot. For some reason, I thought I had to specify the name of the array based on my research. array[0] for the first item and array.length-1 for the last. I'm pretty new to all of this. Thank you for your help! – Hysteresis Aug 05 '16 at 15:57