javascript - Adding event listeners to dom dynamically -
i have created small script having objective calculate body mass index (bmi) based on input values. script looks this:
var config = { "imc": { "weight": { "selector": "#weight", "triggers": [ "click", "focusout", "keyup" ] }, "height": { "selector": "#height", "triggers": [ "click", "focusout", "keyup" ] }, "result": { "selector": "#imc", "triggers": [ "click", "focusout" ] } } }; $.each( config.imc, function( name, attributes ) { console.log('adding events dom elements...'); var selector = $(attributes.selector); $.each( attributes.triggers, function( index, trigger ) { selector.on(trigger, function(){ console.log('calculating...'); }); }); });
then example, when user set text in of fiels (#weight, #height, #imc), message "calculating" should displaying in console (according triggers), problem... message never printed. not same message "adding events dom elements...", print correctly.
it seems have not added dom. need add dom before adding listeners them
for example:
adding dom:
$("<div id='mydiv'>").appendto(container);
then adding listener
$("#mydiv").on("eventlistener",function(){ .... });
Comments
Post a Comment