0

I have a button which redirects the user to the previous page:

<button id="back" onclick="location.href='..'">Back</button>

And I want to change his location to two pages before.

What's wrong with this code?

document.getElementById("back").setAttribute("onclick", function(){window.location.href='../../'});

or this

document.getElementById("back").addEventListener("click", "location.href='../../'");

or this

document.getElementById("back").onclick="location.href='../../'";

for some reason none of them work properly and my button remains unchanged... Google doesn't help!

5 Answers5

1

Try

document.getElementById("back").addEventListener("click", function(){
  window.location.href='../../';
});
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You can do like below

<button id="back" onClick="GoBack()">Back</button>

<script>
   function GoBack(){
     window.location.href='../../';
   }
</script>

And If you want to go back to the previous page you can do like bellow

<button id="back" onClick="GoBack()">Back</button>

    <script>
       function GoBack(){
         window.history.go(-2);
       }
    </script>
Faiz Sandhi
  • 306
  • 2
  • 12
  • I cannot change the original button because I need it into other pages –  Mar 17 '20 at 10:53
0

I think this is better

document.querySelector("#back").addEventListener("click", () => window.history.go(-2));
PatrickMahomes
  • 844
  • 1
  • 6
  • 8
0

you can use this windows.history.go(-2);:

<button onclick="windows.history.go(-2)">Back</button>

or save address of previous pages and reference to them.

Reundo
  • 141
  • 1
  • 5
  • I want to go two pages before in the url tree (es.`root/page1/page2/mypage`->go from `mypage` to `page1`), not backwards into the history –  Mar 17 '20 at 10:52
  • @Fox sorry. seems i didn't understand the question well:) – Reundo Mar 17 '20 at 10:56
0
  1. setAttribute for onclick doesn't works in some browsers. Read about it here.

  2. Syntax for addEventListener is

target.addEventListener(type, listener [, options]);

Read about it here

So, Working code

document.getElementById("back").addEventListener("click", function(){
  window.location.href='../../';
});
Dum
  • 1,431
  • 2
  • 9
  • 23