javascript tutorial - [Solved-1 Solutions] Event binding on dynamically - javascript - java script - javascript array



Problem:

Event binding on dynamically created element?

Solution 1:

we should use jQuery.fn.on:

$(staticAncestors).on(eventName, dynamicChild, function() {});
click below button to copy the code. By JavaScript tutorial team

Prior to this,the recommended approach was to use live :$(selector).live( eventName, function(){} );

However, live() was deprecated in 1.7 in favour of on(), and completely removed in 1.9. The live() signature:

$(selector).live( eventName, function(){} );
click below button to copy the code. By JavaScript tutorial team

... can be replaced with the following on() signature:

$(document).on( eventName, selector, function(){} );
click below button to copy the code. By JavaScript tutorial team

For example, if our page was dynamically creating elements with the class name dosomethingwe would bind the event to a parent which already exists, often document.

$(document).on('mouseover mouseout', '.dosomething', function(){
    // what we want to happen when mouseover and mouseout 
    // occurs on elements that match '.dosomething'
});
click below button to copy the code. By JavaScript tutorial team

Any parent that exists at the time the event is bound is fine. For example

$('.buttons').on('click', 'button', function(){
    // do something here
});
click below button to copy the code. By JavaScript tutorial team

would apply to

<div class="buttons">
    <!-- <button>s that are generated dynamically and added here -->
</div>
click below button to copy the code. By JavaScript tutorial team

Related Searches to javascript tutorial - Event binding on dynamically