10
votes

I have an anchor tag (namely Cancel button) with a class attribute and href attribute in a jsp file .

I have written an onclick event for the class attribute in a seperate js file. So when the button is clicked, the onclick event executes and then takes to the href link.

When the button is clicked more than once it takes me to an empty page or an error page.

I want to prevent more than one click on the button.

I have tried using event.preventdefault() function inside my onclick() function but the href link is not working if I do that. Any other way?

My JS code:

$('.cancel-btn').on('click',function(evt){
            //evt.preventDefault();
           //My Code            

        });
5
Have a look into the jsfiddle jsfiddle.net/w2wnuyv6/1Shiladitya

5 Answers

11
votes

jQuery one() method will perform click event only once:

$('.cancel-btn').one('click',function(evt){
  // evt.preventDefault();
  // code here            
});

Also possible using jQuery on() method that may be more useful when the event should be removed conditionally:

let count = 0; // or may be a boolean flag
$('.cancel-btn').on('click', function(evt){
  if (count == 0) {
    count++;
    // code here
  } else {
    return false;
    // or evt.preventDefault();
  }
});

Or like this:

$('.cancel-btn').on('click', function(evt) {
  // code here
  // then remove the event handler.
  $(this).off('click');
});
5
votes

Try using a boolean flag to make sure the function executes only once

var executeOnce = false;
$('.cancel-btn').on('click',function(evt){
   if(!executeOnce){
     //evt.preventDefault();
     //My Code  
     executeOnce = true;
   }     
});
3
votes

Here you go with one more way to do it using pointer-events as none https://jsfiddle.net/w2wnuyv6/1/

$('a[value="cancel"]').click(function(){
    $(this).css({
        'pointer-events': 'none'
    });
});
1
votes

you can write a function like this:

function clickOnce (element ,listener){
    element.addEventListener("click", function (event){
        listener(event);
        element.removeEventListener("click", arguments.callee);
    });
}

jsfiddle

1
votes

As you mentioned the event is written on that class, you can use this simple code to ensure that its clicked only once:

$('.cancel-btn').on('click', function(evt) {
  // execue your code
  $(this).removeClass('cancel-btn');
});

This code will remove the class from the DOM and hence the click event will never get fired.

Optionally, You can use off() to remove an event like so:

$(".cancel-button").off("click");

This will remove all click events bound to this element. In your code, it would be like:

    $('.cancel-btn').on('click', function(evt) {
      // execue your code
      $(this).off("click");
    });