jQuery - Proper way to rebind existing function after new item added to DOM -


i want rebind existing function after draggbale item dropped, like:

.item draggable item, , .droppable droppable area.

i running function .droppables .item on .ready(), if drop .item .droppable existing function not work newly dropped .item, put event inside function, like:

function my_event(){     jquery('.droppable').on('mouseover.mine mouseout.mine', function (e) {             if ($(this).is(".active")) {                 e.stoppropagation();                 e.preventdefault();                 jquery(this).toggleclass('highlight');             }         }).on('click.mine', function(e){             if ($(this).is(".active")) {                 e.stoppropagation();                 e.preventdefault();                 show_data(this);             }         });     }); } 

now, can call function on .ready() , .droppable() event stop. working fine,

but want ask right call , rebind function after every .item dropped ? if no please tell me how in proper way.

there no 'right' or 'wrong' way things, though there more efficient methods. solution need delegated event handling, events handled once they've propagated parent element, thereby getting rid of need rebind handler new child elements.

let's of .droppable elements contained in .parent element, , new ones added there.

your handler like

jquery('.parent').on('mouseover.mine mouseout.mine', '.droppable', function (e) {     if ($(this).is(".active")) {         // etc...     } } 

the jquery docs on helpful in understanding logic.

update

as note in comment, rest of code have adjust change, since e.stoppropagation(); definition @ odds concept of delegated event. current approach have re-tooled like

jquery('.parent').on('mouseover.mine mouseout.mine', '.droppable', function (e) {      // original child triggered event     var activeelem = $(e.target).closest('.droppable');      if ($(activeelem).is(".active")) {         e.stoppropagation();         e.preventdefault();         jquery(activeelem).toggleclass('highlight');     } } // etc 

if you've never used them, read on closest , event.target.


Comments

Popular posts from this blog

javascript - DIV "hiding" when changing dropdown value -

Does Firefox offer AppleScript support to get URL of windows? -

android - How to install packaged app on Firefox for mobile? -