JQuery - how to remove .submit () and .focus () events

The function that contains these events is called every time the popup is opened

I have a function that I need to call multiple times on a page. The function contains several events .on("click", function....

.

To keep me from adding more and more clicks to the same element, I precede each one .on("click",

with .off("click",

, which (I understand) is the correct way to handle this?

My function also has this: $("#myForm").submit(function(e){...

And also ... $("#myTextArea").focus(function(e){...

My questions are: Do I need to "decouple" (I don't want a better word) .submit and .focus functions in the same way that I execute the "click" function to stop these events, multiplying them by each element on every function call?

And if so, what is the correct way to do it?

Many thanks

John :-)

** Update ** I've included a little more detail upon request.

My page includes 3 popups triggered by 3 separate buttons. Pop-ups only start life with "load.gif". On each button click, I check if "loading.gif" is active on the window, and if so, I use an ajax request to fetch the correct HTML for that window.

As soon as my ajax request comes back with HTML, I add it to the window and then call this function to bind events to the corresponding buttons / forms, etc.

If they close that window and open one of the other popups, then I need to call this function again, so I want to avoid incrementing the number of events for each HTML element. Therefore, before putting them back .on

, I first flip the events .off

.

Hope that clarifies the reasoning behind the question, but feel free to ask if it's not clear. I also find it appropriate to point out that I'm new to jQuery (actually actually javascript in general), so this is definitely not the best / only way to achieve this functionality. This is exactly what made sense to me while writing the code.

Initially I had popups prefilled with HTML but hidden, but I found that my page size was quite large and I wanted to improve load times, etc.


+3


source to share


2 answers


You can do what you do. You can also use jQuery's delegation system.

Example:

You have a div (call it #test

) and you add some buttons to it. You remove buttons, you add them again ... But you want to bind a click event to them. You can do it:



$('#test').on('click', 'button', function(event) {
    // Do what you want. this == the clicked button
    $(this).css('background-color', 'red');
});

      

Explanations:

The click event is attached to #test

, but jQuery will check the target target using the css selector button

. And the this

target (not #test

) will click . This way you only create your listener once and you don't need to add / remove it every time you create the button.

+5


source


Try to use preventDefault

.



$("#myForm").submit(function(e){
   e.preventDefault();
   //to do anything
});

      

+3


source







All Articles