17

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?

Nips
  • 13,162
  • 23
  • 65
  • 103

2 Answers2

37

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/

Blazemonger
  • 90,923
  • 26
  • 142
  • 180
  • +1 Nicely simple and straight – Adriano Carneiro Sep 14 '12 at 21:08
  • 2
    It should be noted that use of `document` is not generally a good idea if it can be avoided. For performance reasons, you want to use the closest common static ancestor element. – James Montagne Sep 14 '12 at 21:10
  • Yes, that's worth noting -- although I wasn't going to go into that just now, since it was clearly a new concept to OP, and the difference in typical use is insignificant. – Blazemonger Sep 14 '12 at 21:10
-1

That code could help:

$('input').live('focus', function() {
    $('label span').text('focus');
}).live('blur', function() {
    $('label span').text('blur');
});


Usage example: http://jsfiddle.net/CPQ37/

Michael
  • 1,067
  • 8
  • 13
  • 1
    .live was discontinued since v1.9: http://stackoverflow.com/questions/14354040/jquery-1-9-live-is-not-a-function – meataxe May 30 '16 at 02:14