0

what would be the best way to enable and then re-enable and image click with jquery?

I can diasble the click event easy enough

$(document).on("click", "#rightPager", function () {

if (condition) {
    $(this).click(false);
  }
});

how would I go about in 'enabling' the click event again based on a certain condition?.

I would want to enable the button again for example

$(document).on("click", "#leftPager", function () {
$("#rightPager").click(true);

});
1
  • i dont really get your question. Do you mean you want to disable the actuall onclick event from time to time? Commented Mar 6, 2015 at 14:45

3 Answers 3

1

In order to rebind you would need to use the original .on("click") event again.

Write a function to bind an event to your image:

function bindImage() {
  $(img).on("click", function() {
   // Your bind event goes here
  });
}

Then write a conditional to unbind the event on the image if your condition returns true, then if its false, rebind the event to the image as normal.

if (condition) {
  $(img).unbind();
} else {
  bindImage();
}

Alternatively, you could complete this within a single function such as:

$(document).on("click", "#rightPager", function () {
  if (condition) {
    // terminate the function
    return false;
  } else {
    // put your function here to run as normal
  }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Try to use jQuery off method.

JSFiddle

$(document).off('click', '#rightPager');

Full code:

var condition = true;

$(document).on("click", "#rightPager", function () {

    if(condition){

        alert('Click was disabled');
        $(document).off('click', '#rightPager');
    }
});

Comments

1

you disable the default event by:

$(document).click(function(e) {
     e.preventDefault();
    condition ? doSomething() :  doSomethingElse();
});​

so basically is not that you enable then disable, you prevent the default action, check for your condition and they execute appropriate function

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.