views:

49

answers:

1

Hi

I'm trying to attach a simple focus/blur event listener via the .live() jQuery method to my inputs but what I'm noticing is that the focus event is not firing whereas the blur event is.

Strange… was hoping you may have an idea of why this is happening.

Here is the code:

function rowHighlight() {
  var form = $('form.register'),
      ele = {};

      form.find('label').each(function(i) {
        var link = this.htmlFor;
        form.find('label[for='+link+'],input[name='+link+'],textarea[name='+link+']').wrapAll('<span class="row"/>');
      });

      ele.row = $('form > .row');
      ele.inputs = ele.row.find('input');


      $.each(ele.inputs, function(i) {
          $(this).focus(function() {
              console.log('hello'); // this will fire.
          });
        $(this).live('focus blur', function(e) {
            console.log('current event type: '+e.type); // the focus on this will not fire!?
            ( e.type=='focus' ? console.log('focussed') : console.log('blurred') )
        });
      });    
}
rowHighlight();

$(this).focus… was just put it as a debugging thing and removing it does not make the focus on the live listener work…

Any help would be appreciated.

Thanks for stopping by.

Jannis

+1  A: 

Try changing this line:

$.each(ele.inputs, function(i) {

to this line:

ele.inputs.each(function() {

Explanation:

There are two forms of each() in jQuery.

Iterating over a map or array:

$.each([1,2,3], function(index, value){

});

or, when iterating over a jQuery object:

$("a").each(function(){

});

http://api.jquery.com/jQuery.each/

$(this) means what you would expect only in the second use:

$("a").each(function(){
    $(this).remove();
});

Live vs. Bind:

$("a").click(someClickEventHandler);

... binds the someClickEventHandler click event handler to every a tag that exists when this is executed.

$("a").live("click", someClickEventHandler);

... binds the someClickEventHandler click event handler to every a tag that exists when this is executed, AND it will also bind the someClickEventHandler click event handler to every a event that will ever exist. For example, if an a tag is created from an Ajax response, the event handler will automatically be bond.

SimpleCoder
Thank you very much, this worked wonderfully though the `.live` still wouldn't work. Changing `.live` to `.bind` however made it work.
Jannis
`live()` binds an event handler automatically when passed a selector it should target, not a specific object. See my edit.
SimpleCoder
Thanks for the Live vs Bind addition! Much appreciated.
Jannis
Sure, no problem
SimpleCoder