Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use focus and blur on dynamic inserted elements? [duplicate]

Tags:

jquery

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?

like image 676
Nips Avatar asked Sep 14 '12 21:09

Nips


People also ask

How to bind click event in JavaScript for dynamically added HTML element?

Attaching the event dynamicallyclassName = 'dynamic-link'; // Class name li. innerHTML = dynamicValue; // Text inside $('#links'). appendChild(li); // Append it li. onclick = dynamicEvent; // Attach the event!

What is blur () in Javascript?

The blur() method removes focus from an element.

What is focus and blur?

The blur event fires when an element has lost focus. The main difference between this event and focusout is that focusout bubbles while blur does not. The opposite of blur is focus . This event is not cancelable and does not bubble.

What is blur event in angular?

A blur event fires when an element has lost focus. Note: As the blur event is executed synchronously also during DOM manipulations (e.g. removing a focussed input), AngularJS executes the expression using scope.


1 Answers

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/

like image 123
Blazemonger Avatar answered Sep 28 '22 18:09

Blazemonger