I want to delay a link for a period of 500 with javascript

25,833

Solution 1

Set your href attribute as href="javascript:delay('URL')" and JavaScript:

function delay (URL) {
    setTimeout( function() { window.location = URL }, 500 );
}

Solution 2

If you want to delay every link on your page, you can do it with jQuery like this

$(function(){
    $("a").click(function(evt){
        var link = $(this).attr("href");
        setTimeout(function() {
            window.location.href = link;
        }, 500);
    });
});
Share:
25,833
ammonhra
Author by

ammonhra

Updated on July 16, 2022

Comments

  • ammonhra
    ammonhra almost 2 years

    I've been looking through the Stackoverflow questions, trying to get help with a simple link delay; I want to put it around a div, and I can't make heads or tails of the examples I've found.

    So far, I understand that I need to halt the native function of href, but I don't know how to do that. The code is still very alien to me. Help?

    • VisioN
      VisioN over 11 years
      What do you mean by "delay a link"?
    • mxgr
      mxgr over 11 years
      Do you mean a time delay that occurs when the user clicks on a link before the browser navigates to the linked page?
    • Riju Mahna
      Riju Mahna over 11 years
      Please be more specific in the question. Most of it doesn't make much sense. Some example or snippet will be helpful
    • ammonhra
      ammonhra over 11 years
      Yes, mxgr, that's exactly what I mean.
  • ammonhra
    ammonhra over 11 years
    This is going to be a really dumb question, but where do I put this so that it affects a div?
  • gurvinder372
    gurvinder372 over 11 years
    Ohh, in case this is for a div, then make it <div onclick="delay ('www.google.com')">Click here to go to google in half a second</div>
  • ammonhra
    ammonhra over 11 years
    Oh wait, I just realized what to do. Thanks.
  • Rune Vejen Petersen
    Rune Vejen Petersen over 8 years
    For this to work, you will need add evt.preventDefault(); in the beginning of your function.
  • user2840467
    user2840467 about 8 years
    This works great for me - quick question: Should the () in setTimeout function() have the URL as a parameter too though?
  • Berry M.
    Berry M. over 7 years
    This does not support target="_blank", or any other target setting.
  • lolcatzftw
    lolcatzftw about 2 years
    This does not really answer the question. If you have a different question, you can ask it by clicking Ask Question. To get notified when this question gets new answers, you can follow this question. Once you have enough reputation, you can also add a bounty to draw more attention to this question. - From Review