Need to NOT activate .blur() on input if clicking on a certain element
I've been writing my own auto-suggest, instead of it just filling in the form input it actually produces a HTML list of links and pictures which it gets straight from the AJAX request. One problem I have ran into is that I need to hide the produced list if the input loses focus, but this also happens if you attempt to click a link inside the produced list and it disappears without registering the click.
Here is my code:
var delay = false;
var landing = $('#suggestions');
$('#suggest').keyup(function(e) {
if (e.keyCode > 40 || e.keyCode == 8) { //If a letter or backspace
if(this.value.length >= 3) { // if > 3 characters in the input
$(this).addClass('loading');
clearTimeout(delay);
var query = this.value;
delay = setTimeout( function() {
$.ajax({
url: '/response.php', //returns HTML
type: 'get',
data: { 'q' : query },
dataType: 'html',
success: function(data) {
$('#suggest').removeClass('loading');
landing.show().html(data);
}
});
}, 200);
} else {
landing.empty();
}
}
})
.focus(function() {
if($(this).val() == 'Search...') {
$(this).val('');
}
if($(this).length) {
landing.sh开发者_JAVA百科ow();
}
})
.blur(function() {
if(this.value.length) {
setTimeout(function() {
landing.hide();
}, 150)
} else {
$(this).val('Search...');
}
})
.attr('autocomplete', 'off');
The .blur() is where the problem is being caused, I attempted to add a timeout but this has proven to be quite unreliable.
Additionally, any comments/suggestions to improve what I written so far would be appreciated!
After lots of experimenting the best solution I have came up with is toggle a 'persist' variable on the #suggestions
landing <div>
, so the `blur()`` will do nothing if the user is doing something on the #suggestions box:
$('#suggest').blur(function() {
if(this.value.length) {
if(landingPersist == false) {
landing.hide();
}
} else {
$(this).val('Search Knowledge Base');
}
})
$('#suggestions').mouseover( function() {
landingPersist = true;
})
.mouseout(function(){
landingPersist = false;
});
This method requires no live() or timers which I think is a good thing.
With a check for the persist variable in the blur()
of #suggest
. This met
First, add global varible (outside any function) like this:
var _hideLandingTimer = 0;
Second, change the code in the blur
:
_hideLandingTimer = setTimeout(function() {
landing.hide();
}, 150);
And finally have this:
$('#suggest a').click(function() {
window.clearTimeout(_hideLandingTimer);
});
This will clear the timer (thus not hide the landing) in case link is clicked,
精彩评论