简体   繁体   中英

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.

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>

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);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM