0

When the button is clicked I need the page to wait for .8s to open the link in the same window, due to a site animation.

This time out code below only works if the href target is _blank and not if the target is the default _self - the link then becomes undefined.

$("#button").click(function() {

  setTimeout(function(url) {
    window.location = url;
  }, 800, linkUrl);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<a href="https://www.w3schools.com"><button id="button">Click</button></a>

How can I fix my code so that it will wait for .8s before the new link is open in the same window when the button is clicked?

Dmitry
  • 6,716
  • 14
  • 37
  • 39
Fjott
  • 1,107
  • 3
  • 15
  • 38

2 Answers2

1

You trigger the anchor href if you click on the button. Just remove the a tag and set the window.location.

$("#button").click(function() {

  setTimeout(function() {
    window.location = "https://www.w3schools.com";
  }, 800);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<button id="button">Click</button>
0

U should use location.href = "url.com" or window.open("url.com") instead of in the tag.

check those posts for deeper understanding Jquery Delay After Click Open URL in same window and in same tab

$("button").click(
    function() {
        console.log("clicked...waiting...");

        setTimeout(
            function() {
                location.href = "https://stackoverflow.com/questions/8752541/jquery-delay-after-click";
            },
            800);
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button type="button">Click Me</button>
Merey Nurlan
  • 295
  • 5
  • 17