Reputation: 398
This is PHP string with is echoed out:
$('.$name input').on( 'blur', function(e){
$('span.$name div ul').on('click', 'li', function(ev){
var value = $(this).attr('value');
var html = $(this).html();
console.log(value);
$('span.$name select').val( value );
$('span.$name input').val( html );
$('span.$name div').hide();
});
});
So I have a handler when its input loses focus and clicked on list item it does some stuff and hides the div, but I want to hide also when input loses focus and its NOT clicked on list element.
If I try to do this:
$('.$name input').on( 'blur', function(e){
$('span.$name div ul').on('click', 'li', function(ev){
var value = $(this).attr('value');
var html = $(this).html();
console.log(value);
$('span.$name select').val( value );
$('span.$name input').val( html );
});
$('span.$name div').hide();
});
It just closes the div and click
event handler doesn't work at all. No errors, nothing.
This doesn't work as well:
$('.$name input').on('blur',
function (e) {
$('span.$name div').hide();
});
$('span.$name div ul').on('click', 'li', function (ev) {
var value = $(this).attr('value');
var html = $(this).html();console.log(value);
$('span.$name select').val(value);
$('span.$name input').val(html);
});
How can I fix my issue?
EDITED:
DEMO: http://jsfiddle.net/e2dw18z0/
Upvotes: 0
Views: 45
Reputation: 4462
I think I can see how you got into this problem. When you leave the input and go to click on the div, the input's hover event closes the div before the click is registered on on the div. So a really quick fix for this is:
$('.test_name input').on( 'blur', function(e){
window.setTimeout(function() {
$('span.test_name div').hide();
}, 100);
});
as demoed here:
http://jsfiddle.net/sifriday/e2dw18z0/1/
The timeout ensures there's time for the div click to register, if it is forthcoming. If not, no problem, and either way the popdown is closed as desired. And as adeneo comments above, this also tidies up your nested event code.
A tidier way to do it is to use a click on the document to close the popdown, but only if the popdown is visible and the input hasn't got focus:
$(document).on( 'click', function(e){
if (
$('span.test_name div').is(":visible") &&
!($('span.test_name input').is(':focus'))
) $('span.test_name div').hide()
});
as demoed here:
http://jsfiddle.net/sifriday/e2dw18z0/3/
Upvotes: 1