javascript - jQuery - how to remove .submit() and .focus() events -


the function holds these events called every time popup window opened

i have function need call several times on page. function contains .on("click", function.... events.

in order don't keep adding more , more click events same element i'm preceding every .on("click", .off("click", (i understand) correct way handle this?

my function has following: $("#myform").submit(function(e){... and... $("#mytextarea").focus(function(e){...

my questions are: need "unbind" (for want of better word) .submit , .focus functions same way "click" function in order stop these events multiplying on elements every time function called?

and, if do, correct way this?

many thanks

john :-)

** update ** have included bit more detail requested.

my page includes 3 popup windows initiated 3 separate buttons. popup windows start life "loading.gif" in them. each button clicked test see if "loading.gif" active in window and, if is, use ajax request fetch correct html window.

once ajax request comes html append window , call function bind events relevant buttons/forms etc.

if close window , open 1 of other popups need re-call function , want make sure i'm not doubling on events each html element. therefore turn events .off first before putting them .on.

hope clarifies reasoning behind question feel free ask if it's not clear. think prudent point out i'm newbie jquery (in fact javascript in general really) not best/only way achieve functionality. it's way made sense me @ time of writing code.

originally had popup windows pre-populated html hidden found page size quite large way , wanted improve load times etc.


you can way doing. can use jquery delegation system.

example :

you have div (let's call #test) , add buttons in it. remove buttons, add them again ... want bind click event on them. can :

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

explanations :

the click event binded on #test, jquery test clicked target against css selector button. , this clicked target (not #test). way create click listener once , don't have add/remove every time create button.


Comments