Nips Nips - 1 month ago 7
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

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/

Comments