PinG
PinG

Reputation: 50

Auto go back after clicking a link in Javascript

When a user click an href link with id="boo" I am trying to get the browser to automatically go 'back' after 2 seconds.

This isn't working and i'm reaching out for some help from you all. Thanks in advance!

document.getElementById("boo").addEventListener("click",
  function a(event) {
    setTimeout(function() {window.location = History.back},2000)}  
);

Edit: (Adding this to clarify my goal) so basically i want to do two things on click. navigate to a different page (time.is) and then automatically go back to the original page after 4 seconds.

Upvotes: 1

Views: 723

Answers (2)

Miu
Miu

Reputation: 844

I think you have to make the default function of <a> tag stop working. Please try adding .preventDefault().

document.getElementById("boo").addEventListener("click",
  function (event) {
    event.preventDefault();
    setTimeout(function() {window.history.back()}, 2000);
  }   
);

If you want to do two things on one click, I suggest this:

  1. Open the other website in a new tab
  2. Go back to a previous page after 2 seconds in an initial tab

JavaScript:

document.getElementById("boo").addEventListener("click",
  function (event) {
    // Remove .preventDefault()
    setTimeout(function() {window.history.back()}, 2000);
  }   
);

HTML:

<a id="boo" class="clock" href="https://time.is/" target="_blank"></a>

Upvotes: 1

gere
gere

Reputation: 1750

A part from a syntax error (history should be lower case), you are setting window.location with the back function, without executing it.

This should fix your code:

document.getElementById("boo").addEventListener("click",
  function(event) {
    setTimeout(function() {window.history.back()}, 2000);
});

Upvotes: 0

Related Questions