-1

My page is supposed to redirect from the root page on my website to one of two different subpages, linked via buttons on the root page. The buttons don't work.

This is my code:

HTML:

<!DOCTYPE html>
<html>
  <head>
    <title>My name</title>
    <link rel="stylesheet" href="styles.css">
    <script src="js.js"></script>
  </head>
  <body>
    <div class="navbar">
      <input type="button" class="button" value="My GitHub portfolio" onclick="page1();">
      <br>
      <input type="button" class="button" value="Start Page" onclick="page2();">
    </div>
  </body>
</html>

JS:

var pageto;

function page1(){
    var pageto = 1;
    reload();
};

function page2(){
    var pageto = 2;
    reload();
};

function reload(){
    if (pageto == 1){
        location.href('personal-website');
    }
    else if (pageto == 2){
        location.href('start-gp');
    };
};
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Could you expand on *"buttons don't work"*? Any errors in the console? href isn't a method, for one thing; see e.g. https://developer.mozilla.org/en-US/docs/Web/API/Location. – jonrsharpe Dec 22 '19 at 19:06

2 Answers2

0

The first problem is, that you redeclare the pageto variable inside page1 and page2, so the reload function can't access it.

You can remove the var keyword before the assignment, to set the global one (not recommended):

var pageto;
function page1(){
    pageto = 1;
    reload();
};

function page2(){
    pageto = 2;
    reload();
};

Or, pass it as an argument to reload. That way you can avoid creating unnecessary variables:

function page1(){
    reload(1);
};

function page2(){
    reload(2);
};
function reload(pageto){
  //Contents of reload function
};

The second problem is the the location.href property contains the URL of the page, and it is not a function. You can redirect the page by assigning the new URL to it:

function reload(){
    if (pageto == 1){
        location.href='personal-website';
    }
    else if (pageto == 2){
        location.href='start-gp';
    };
};

Alternatively, you can use the window.open method, to redirect the browser:

function reload(){
    if (pageto == 1){
        window.open('personal-website','_self');
    }
    else if (pageto == 2){
        window.open('start-gp','_self');
    };
};

Or the similar location.replace:

function reload(){
    if (pageto == 1){
        location.replace('personal-website','_self');
    }
    else if (pageto == 2){
        location.replace('start-gp','_self');
    };
};
FZs
  • 16,581
  • 13
  • 41
  • 50
0

function redirect(el){
    location.href = el.getAttribute("data-url");
}
<input type="button" class="button" value="My GitHub portfolio" onclick="redirect(this)" data-url="personal-website">
<br>
<input type="button" class="button" value="Start Page" onclick="redirect(this)" data-url="start-gp">
Ahed Kabalan
  • 815
  • 6
  • 8