开发者

Focusout or blur on class element

开发者 https://www.devze.com 2023-02-01 01:44 出处:网络
I\'m trying to change the class of an input element when it loses focus. The whole premise of this project is to allow the user to double-clic开发者_如何学编程k some text and then be able to edit that

I'm trying to change the class of an input element when it loses focus. The whole premise of this project is to allow the user to double-clic开发者_如何学编程k some text and then be able to edit that text. Then when they lose focus on the field, it should look like it's not part of a form.

my problem lies here:

$('.actdblclk').dblclick(function(){

    $(this).removeClass('actdblclk').addClass('actdblclk_active').focus();

});

$('.actdblclk_active').focusout(function(){
    alert();

    $(this).removeClass('actdblclk_active').addClass('actdblclk');
});

I gain focus on the input field when I double click, but when I click off, the focusout event does not fire.

Here is the whole fiddle http://www.jsfiddle.net/t8JsG/


The focusout() event handler doesn't fire, because at the moment it was assigned there was no element with a class .actdblclk_active.

You should assign a focusout() handler inside dblclick(), like this:

$('.actdblclk').dblclick(function(){
  $(this).removeClass('actdblclk').addClass('actdblclk_active').focus();
  $(this).focusout(function(){
    alert();

    $(this).removeClass('actdblclk_active').addClass('actdblclk').unbind('focusout');

  }) 
});

Update: Second option is to assign focusout() handler using jQuery.live(), like this:

$('.actdblclk_active').live('focusout', function(
  alert();
  $(this).removeClass('actdblclk_active').addClass('actdblclk');)
});

This way this handler will be assigned to current and any future elements that match .actdblclk_active selector


You can add the handler as a live event handler. This way, the live handler is always looking for events within the matched selector.

$('.actdblclk').dblclick(function(){

    $(this).removeClass('actdblclk').addClass('actdblclk_active').focus();

});

$('.actdblclk_active').live('focusout', function(){
    $(this).removeClass('actdblclk_active').addClass('actdblclk');
});


There are no elements on the page with the class actdblclk_active when the page loads.

You should assign the focusout handler using the original class:

$('.actdblclk').dblclick(function(){     
    $(this).removeClass('actdblclk').addClass('actdblclk_active').focus();
}).focusout(function(){
    $(this).removeClass('actdblclk_active').addClass('actdblclk');
});
0

精彩评论

暂无评论...
验证码 换一张
取 消