Reputation: 14747
I have created a small script having as objective calculate the body mass index (BMI) based on input values. The script looks like 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 to dom elements...');
var selector = $(attributes.selector);
$.each( attributes.triggers, function( index, trigger ) {
selector.on(trigger, function(){
console.log('calculating...');
});
});
});
Then for example, when the user set the text in some of the fiels (#weight, #height, #imc), the message "calculating" should be displaying in console (according to triggers), but that is the problem... the message is never printed. As not the same with the another message "adding events to dom elements...", it does print correctly.
Upvotes: 1
Views: 338
Reputation: 698
One more way is before adding elements to DOM you can set up listeners like the below code.
$(document).on(eventName, selector, function(){});
Beware of the performance implications of the above code. But this will be very much useful in dynamic DOM element creations and avoid messing up with hooking events after adding to DOM.
Upvotes: 1
Reputation: 2907
It seems you have not added the DOM. you need to add DOM before adding listeners to them
for example:
Adding DOM:
$("<div id='myDiv'>").appendTo(container);
then Adding listener to that
$("#myDiv").on("eventListener",function(){
....
});
Upvotes: 1