JQuery removes and adds click event

Is it possible to remove than add a click click event to a specific element? iee

I have $("#elem").click(function{//some behaviour}); , $(".elem").click(function{//some behaviour}); (there is more than one element), and my other getJson function getJson executed. I want to remove the click event from #elem and add it again after receiving from the getJson function, but keep both mouseenter and mouseleave events all the time?

Or maybe create an overlay so as not to click, as in modal windows? is this a better idea?

edit:

I saw some really good answers, but there is one detail that I did not specifically miss. There are more than one element, and I call the click function on className, and not on elementId, as I pointed out in the original question

+4
source share
4 answers

Instead of using unbind () , that means you have to reinstall the same event handler later, you can use jQuery data () with ajaxStart and ajaxStop so that your elements ignore click events during all AJAX requests:

 $(".elem").click(function() { if (!$(this).data("ajaxRequestPending")) { // some behaviour } }).ajaxStart(function() { $(this).data("ajaxRequestPending", true); }).ajaxStop(function() { $(this).removeData("ajaxRequestPending"); }); 

EDIT:. This answer is also an id-to-class proof (see editing the questionnaire), since anything matching the selector will correctly handle AJAX events. This is the main selling point of jQuery, and it shows.

+6
source

You are looking for .unbind() . Pass it a 'click' and it will destroy the click event.

I would put it in front of your getJSON and bind the click event inside the success handler of your ajax call.

+2
source

You need to do some additional scripts. There is no callback for this. Take a look here: jQuery - How to temporarily disable the onclick event listener after the event has been fired?

0
source

Instead of disabling / binding the click event, you can check the state of another variable to see if it should perform the action.

 var MyObject = { requestActive = false; }; function MyJsonFunction() { // when requesting MyObject.requestActive = true; //... // when request over MyObject.requestActive = false; } $("#elem").click(function{ if (MyObject.requestActive == true) { //do something } }); 
0
source

Source: https://habr.com/ru/post/1338166/


All Articles