简体   繁体   中英

Make a link unclickable for a certain amount of time

I have a link that resends an email, but I don't want to let people be able to spamclick the link.

So I figured I need to make it unclickable for 5 minutes after it has been clicked.

I found out how to disable the click function like this:

$('a').click(function(){ return false})

or this:

$('a').removeAttr('href')

But how can I make sure if it is clicked the first time, people cannot click it again for 5 more minutes? And show an alert when it is clicked in the meantime?

Can this be done with jquery?

Rather than removing the href (which can cause annoying behaviour in some browsers) - you could leverage jquery's .one to attach a disabling event handler, and then remove it 5 minutes later.

Combined with pre-defining the original event handler, we can then revert back to behaviour before we initially clicked the link.

(function($) {
    var lockLink = function() {
        var link = $(this);

        link.on('click', function(event) {
            event.preventDefault();
            return false;
        });

        window.setTimeout(function() {
            link.off();
            link.one('click', lockLink);
        }, 300000);
    };

    $('document').ready(function() {
        $('a').one('click', lockLink);
    });
})(jQuery);

Use the setTimeout function:

$('a').on('click', function()
{
    var href = $(this).attr('href');

    $(this).removeAttr('href');

    setTimeout(function()
    {
        $(this).attr('href', href);
        alert('can now click me')
    }, 1000 * 60 * 5); // 1000 milliseconds * 60 = minutes * 5 = 5 minutes
})

You can make use of the data method to store on the element the last time it was clicked.

 $('#clickme').on("click",function(e){ let lastClicked = $(this).data("lastclicked"); if(isNaN(lastClicked) || (new Date() - lastClicked) > (5*1000*60)){ $(this).data("lastclicked", new Date()); return true; } alert("You cant click for 5 minutes") e.preventDefault(); return false; }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="#" id="clickme">Click me</a> 

You could add to this the use of localStorage to make it persist between page loads too, but unfortunately that is not demonstrable using stack snippets.

To do this you could pre-populate data from localStorage on page load

$('#clickme').data("lastclicked",localStorage.lastClicked);

and remember to write to it too:

 if(!lastClicked || (new Date() - lastClicked) > (5*1000*60)){
      var now = new Date();
      localStorage.lastClicked = now;
      $(this).data("lastclicked", now);
       return true;
   }

Final code:

let delay = 5*1000*60; // five minutes

$('#clickme')
    .data("lastclicked",localStorage.lastClicked || 0)
    .on("click",function(e){
       let lastClicked = $(this).data("lastclicked");
       if(isNaN(lastClicked) || (new Date() - lastClicked) > delay){
          var now = new Date();
          localStorage.lastClicked = now;
          $(this).data("lastclicked", now);
          return true;
       }
       alert("You cant click for 5 minutes (" + (delay - (new Date() - lastClicked)) + "ms remaining)")
       e.preventDefault();
       return false;
    });

Live example: https://jsfiddle.net/7tpcyms6/

It's good to give the user some visible indication that the link is disabled. Conveniently, your code can also use that indicator to determine whether the link should be disabled or not:

 $('#foo').click(function() { var $el = $(this); if ($el.hasClass('disabled')) { // The link is disabled return false; } else { // The link is enabled; do whatever it is supposed to do here // ...then disable the link: $el.addClass('disabled'); // ...and re-enable it in five seconds: window.setTimeout(function() { $el.removeClass('disabled') }, 5000); } }); 
 .disabled { /* Adjust to taste */ cursor: default; text-decoration:none; color: #CCC; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="foo" href="javascript:console.log('Clicked')">Click me</a> 

This method avoids some UI issues that would arise from removing the href, and can cycle on and off as many times as necessary (a number of the other answers you've received here will only work once.) It does not prevent the user from bypassing the timeout by opening multiple windows or reloading the page; if you truly need to enforce the delay you'll need to handle this serverside rather than in-browser.

The most simple way to achieve your goal is to register a function and remove it after the timeout:

 var disabledClick = function(){ return false }; $('a').on( "click", disabledClick ); setTimeout(function(){ $('a').off( "click", disabledClick ); }, 2000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="www.google.com"> ask google</a> 

Example: https://jsfiddle.net/xc1ra31a/

<a href="http://www.anylink.com" id="anyLink">Any Link</a>

<script>
$('#anyLink').on('click', function(){
    var href = $("#anyLink").attr('href'); //for further use
    $("#anyLink").removeAttr('href');
var d = new Date();
var time = d.getTime();
var after_time = time + 300000; //added 5 minutes to current time.
});

link is disabled now. make an ajax call here to save the state of link in DB or you can use localstorage as per your requirements.

And store current_time + 5 minutes in storage and check if current time is >= to the one which we stored earlier. and then make the link clickable again.

var d = new Date();
var time = d.getTime();
    if(time >= after_time) {
        $("#anyLink").attr('href', href); //clickable now   
    } 


</script>

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