Search code examples
javascriptarraysfunctionswitch-statementincrement

Javascript increment a variable in a function


Hey guys I'm new to programming, I need to make a website for school. I want to open the next page when pressing the arrow keys. So I thougt, I can put the URLs into an array an increment the index, when the button is pressed. Unfortunately I get some random numbers from 1 to 3 when I press the down key.

const url = ['/#t1', '/#t2', '/#t3', './contact.html', './404.html'];

var index = 0;

$(document).keydown(function(e) {
    switch(e.which) {
       case 38: // up
           up();
       break;

       case 40: // down
           down();
       break;

       default: return; 
   }
   e.preventDefault();
});

function up() {
    index = index - 1;
    alert(index);
    window.location.href = url[index];
}

function down() {
    index = index + 1;
    alert(index);
    window.location.href = url[index];
}

Solution

  • A quick way to solve this without using storage is to find the index in the array rather than keeping track of it. You can do that like so:

    const url = ['/list', '/of', '/urls'];
    
    //find index of current url in array
    let index = url.indexOf(window.location.pathname)
    
    if(index == -1){
     //url is not in the array
     windows.alert("invalid url")
    }
    

    Edit: I agree with Michael Geary that is is a bad idea for a real world website