4

I have a link which on click opens a modal popup. If the network connection is slow it takes sometime to open the popup. And if the user is super fast, he might click the link multiple times and their are multiple popups coming on the screen. I want to prevent user's multiple click on the link.

I disabled the link on the first click. but the problem is when the popup is closed , it doesnt enable the link again.

How do i prevent these multiple clicks nd make sure that when the popup is not shown, the link is enabled.

$('#link').click(function() {
    $(this).attr("disabled", "disabled");
    $("#popup").show();
});
Aman Gupta
  • 1,764
  • 4
  • 30
  • 58

5 Answers5

6

You can use a flag variable to keep track of whether the link has been already clicked or not, and allow click event callback to execute only if is hasn't been clicked before.

var isClicked;   
$('#link').click(function() {
   if(isClicked){
     return false;
   }
   isClicked = true; 
   $("#popup").show();
});

Now you can update isClicked = falsewhere you do $("#popup").hide();

Neeraj Dembla
  • 315
  • 2
  • 12
1

You'll need to use a callback function, and you can place it one one of two places: Either as an argument passed into show() or in whatever script triggers the modal closing.

For adding it to show change:

$('#link').click(function() {
    $(this).attr("disabled", "disabled");
    $("#popup").show();
});

to

$('#link').click(function() {
    var $temp = $(this);
    $(this).prop("disabled", true);
    $("#popup").show(function(){
         $temp.prop("disabled", false);
    );
});

(See Remove disabled attribute using JQuery? for why you should use prop instead of attr

Community
  • 1
  • 1
Fhtagn
  • 753
  • 5
  • 9
1

Enable button on close popup action. Like this:

$( "#popup" ).hide( "slow", function() {
    $("#link").removeAttr('disabled');
  });
Julia
  • 1,301
  • 1
  • 14
  • 29
0

You could just use a setTimeout. Run the function to disable the button once it is clicked, and call a timeout to re-enable it after some time has passed.

Dalton
  • 107
  • 8
0

Using setTimeout and 'pointer-events: none' always get the job done for me.

$('#link').click(function(e) {
  $("#popup").show();
  $(e.currentTarget).css({'pointer-events': 'none', 'cursor': 'not-allowed'});
  setTimeout(() => $(e.currentTarget).css({'pointer-events': 'auto', 'cursor': 'pointer'}), 300);
});
tyronedee
  • 11
  • 1