user1032531
user1032531

Reputation: 26281

Enable and disable click on element

After clicking an element, I would like to disable click() on that element until the user performs some other task. I've seen posts where people say to add the disabled attribute to the element, but that doesn't seem to work for me.

I've seen other posts where they recommend unbinding click(), but then one has to duplicate the code when re-binding the click(). Any suggestions on the best way to do this? Thank you

$("#someElement").click(function(){
    //Disable click on #someElement, do some stuff, and show another element
    $('#anotherElement').show();
});

$('#anotherElement').click(function(){
    //Do some stuff and re-enable #someElement
});

Upvotes: 0

Views: 16309

Answers (3)

AntonB
AntonB

Reputation: 2853

Not sure why this hasn't been posted yet.

Add a class like .is-disabled to the element after it is clicked. When the other action is completed remove that class from the element.

And define that class as follows (92% browser support as of 1/29/2017, http://caniuse.com/#feat=pointer-events):

.is-disabled {
   pointer-events: none;   
}

Upvotes: 1

RobinJ
RobinJ

Reputation: 5243

Just put the code in your click function inside this scope:

if (clickable == true)
{
}

And when the user isn't allowed to click on it set clickable to false. When the user is allowed to click again, set clickable to true again.
Not as professional as Sarfraz's anwser (it wasn't there when I clicked the "Add answer" button, otherwise I wouldn't have posted this probably), but it works and is easy :p

Upvotes: -2

Sarfraz
Sarfraz

Reputation: 382616

You can use bind and unbind:

$("#someElement").click(function(){
  $(this).unbind('click');
  $('#anotherElement').show();
});

$('#anotherElement').click(function(){
  $("#someElement").bind('click');
});

Upvotes: 3

Related Questions