I want to show a button on focusin, do some action when cli开发者_开发知识库cked or hide that button on focusout:
$(".editableDiv").live('focusin', function(){
// show button under the .editableDiv div
$("#button").live('click', function(){
// do action
});
$(".editableDiv").live('focusout', function(){
// hide button
});
});
It shows the button on focus but when the button is clicked, the action is ignored and the button is immediately hidden like if focusout had priority over click. When I try to remove that focusout part, the action gets done but button stays visible... but I need to hide that button on focusout.
It seems so simple... but I cannot figure out why it's not working - any hint would be appreciated.
You need to shuffle your handler assignments around a bit. Right now the button click and focusout handlers are only bound on the first focusin.
On top of that there is the problem of not being able to know (without using IE specific information), what event triggered the focusout (so you can't isolate the button as the source). The best solution appears to be a timeout solution. I'd suggest code such as that provided in this answer to your question.
What's happening is that the focusout is firing and hiding your button before it can receive the click event.
So why not just hide the button on click/focusout after a few milliseconds??
$(".editableDiv").live('focusin', function(){
// show button under the .editableDiv div
$("#button").show();
}).live('focusout', function(){
setTimeout(function(){
$("#button").hide();
},50);
});
$("#button").live('click', function(){
// hide button
alert('test');
$("#button").hide();
});
http://jsfiddle.net/userdude/E2Cyx/2/
It's just that when you click on a button, you're essentially focussing on IT, and therefore, it fires the focusout/blur event for whatever just had the focus.
You need to prevent event propagation on that button click handler, because if not, the buttons gains focus, and the focusout function is invoked.
$("#button").live('click', function(event) {
event.stopPropagation();
//do your thing...
});
精彩评论