I am trying to use an Ajax search\suggest box. I use jQuery to handle the textbox losing focus. However, when I click on a link in the suggestion list jQuery fires the blur event and the link is not followed. Here is the jQuery code:
$(document).ready(function() {
$('#lstxt').click(function() {
this.value = '';
});
$('#lstxt').blur(function() {
this.value = 'Database Search';
document.getElementById('ls').innerHTML='';
document.getElementById('ls').style.border='0px';
});
});
How do I get it to not fire .blur if a link is being clicked inside the suggestion list (id="ls_table")?
var global_switch = false;
$('#ls_table').hover (
function () { global_switch = true; },
function () { global_switch = false; }
)
$('#lstxt').blur(function() {
if (global_switch) { return; } else { ...});
This is just a proof of concept. As always, global variables are bad. Take a look at jQuery's data API to circumvent it.
Cheers,
The method I used when implementing my own is adding a slight delay:
$('#lstxt').blur(function(){
setTimeout(function(){
// original blur code here
}, 250);
});
Definitely not the best solution (but usually works). But Boldewyn's solution should work -- assuming that #ls_table has been created before trying to assign it. If you're creating/destroying #ls_table frequently, you can bind the event to the parent element:
// just using the data API for jquery.
$('#ls').hover(
function(){ $('#ls').data('autocompleteover', 1); },
function(){ $('#ls').data('autocompleteover', 0); }
);
$('#lstxt').blur(function(){
if($('#ls').data('autocompleteover'))
return;
// original blur code here
}
try this code:
$(document).ready(function() {
$('#lstxt').click(function() {
this.value = '';
return true;
});
$('#lstxt').blur(function() {
this.value = 'Database Search';
$('#ls').html('').css('border',"0px");
return true;
});
});
edit:
blur will fire if you click outside of a textbox. is lstxt a textbox?
edit2: you will need to unbind the blur event and rebind it conditionally. i would need more info about your page layout to tell you how to do it
I manage similar problem (with some custom validator on blur, which was fired before click on close button - but I want to close dialog (click) without this blur event fired)
code on input (with validator):
..
$(this).blur({validators: validators}, function(event){ // blur
(function($this){
validator_timeout = setTimeout(function(){ // validator_timeout is global
$this.validate(event.data.validators); // do some validation
}, 50); // delay just minimum of time, but enough to let other event to be fired
}($(this))); // passing $(this) to function
});...
and on other event handler, like close dialog, when we don't want to call function on validate, just clear validator_timeout to suppress blur:
click_function = function(){
clearTimeout(validator_timeout);
$( this ).dialog( "close" );
}
Hope it will be useful for someone.