Nips Nips - 1 year ago 86
jQuery Question

How to use focus and blur on dynamic inserted elements?

I have function:

$(document).ready(function(){

$("input.myclass").focus(function() {
// something
}).blur(function() {
// something
});

}


and html:

<div class="usil">
<div class="editable">
<form>
<input type="text" class="myclass" />
</form>
</div>
</div>


On load page jquery on "myclass" elements work fine but other script add dynamically "usil" class divs and on this divs jquery dont work. How to do it?

Answer Source

Use event delegation:

    $(document).on('focus',"input.myclass", function() {
        // something
    }).on('blur',"input.myclass", function() {
        // something
    });

or

$(document).on({
    'focus': function () {
        // something
    },
    'blur': function () {
        // something
    }
}, 'input.myclass');

http://api.jquery.com/on

http://learn.jquery.com/events/event-delegation/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download