Gelin Luo
Gelin Luo

Reputation: 14393

JQuery event not fired when using "on"

I am creating a web app which using knockout to load page component html (and in turn the javascript of that part). I found a strange problem: when I use $(selector).on('event', handler), then handler will never fired. But if I change it to $(selector).live('event', handler), it will be good. I need to point out that when I call that event binding statement, the $(selector).size() > 0.

The same issue cause my $(selector).validate({onfocusout: validator}) has no effect.

Any ideas?

Upvotes: 2

Views: 228

Answers (1)

Purag
Purag

Reputation: 17071

From what I understand, you are loading this content dynamically, which means you have to use a different syntax for your on() function.

$(document)
    .on("eventName", selector, handler(event){
        // handler
    });

This is a method that employs event bubbling. Instead of binding the event to existing elements, you are binding the event to the document and matching the element on which the event occurred to the selector and letting this event bubble up to the document level.

That being the case, it's better to use as close a parent as possible with this function instead of document. Keep in mind that this parent must exist on the page at load. The reason for this is to optimize performance and run smoother code.

If I understand the purpose of the second snippet, this should do the trick:

$(document)
    .on("blur", selector, function(){
        $(this).validate();
    });

We delegate the blur event to the elements matched by selector and validate them when the event occurs (blur occurs when focus on an element disappears).

Upvotes: 3

Related Questions