jquery - Javascript function overwriting itself -


sorry title isn't clear, i'm not sure problem is. i'll happily rename if has better idea.

i have bunch of boxes classes 'something-box' called clicking various things have given classes of 'something-button'. boxes have class of 'modal-box' , contained within partially transparent div comes cover rest of screen ('modal-blackout'). rather write same code out each 1 (which doing) decided make function attach relevant click handlers each button (and various other things accompany it). have following js code:

    function modal(selector) {         button = $(selector+'-button');         box = $(selector+'-box');         button.click(function(e) {             e.stoppropagation();             $('.modal-box').hide();             $(document).off('.hidedoc');             $('.modal-blackout').show();             box.show();             $(document).on('click.hidedoc', function(e) {                  if (!box.is(e.target) && box.has(e.target).length === 0)                 {                     $('.modal-blackout').hide();                     box.hide();                     $(selector + '-box .error-message').html('');                     $(document).off('.hidedoc');                 }             });             e.preventdefault();         });     }      modal('.password-reset');     modal('.login');     modal('.signup'); 

but every button brings .signup-box (or whichever 1 called last). note if remove function , write out 3 times manually different selectors everywhere in code, works intended.

suspect there fundamental don't understand here. can explain?

you're creating global variables being overridden each time modal() called. results in box referring box selected last selector, , similar button.

for button, it's not problem, since use once. however, reference box has stay accurate, because it's used in click event handler.

replace:

function modal(selector) {     button = $(selector+'-button');     box = $(selector+'-box'); 

with:

function modal(selector) {     var button = $(selector+'-button');     var box = $(selector+'-box'); 

this result in variables being created in modal's scope, subsequent calls modal can't override variables set previous selectors.


Comments

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

jquery - javascript onscroll fade same class but with different div -