How to associate a blur event with a direct click event?

I have this function:

$('input#auto_results').bind('blur', function(e) { $('.result').bind('click', function() { return; }); $('#results_container').hide(); }); 

Basically, I would like the #results_container to hide when eroding UNLESS, push an element with a .result class.

The above function does not work

+4
source share
1 answer

Problem with your code:

What you are trying to do is attach the click event handler to .result in the event handler of another event ( blur ).

Your code will do nothing but attach this click handler, which basically does nothing.


Simple option:

The blur event will .results first, and click on .results second, so this is not an easy situation.

The easiest way to do this:

 $('input#auto_results').blur(function () { $('#results_container').hide(); }); $('.result').click(function () { $('#results_container').show(); }); 

jsFiddle Demo

So, just hiding the container by clicking on it, show it again. Results in a slight blink.


Waiting Option:

Another option I can think of is to set a small timeout when blur fired, and in the click .results event, cancel it. In this example, I save the timeout on the body using the .data() function, you can save it on a more logical element, this is just a demonstration:

 $('input#auto_results').blur(function () { var cucc=setTimeout(function () { $('#results_container').hide(); $('body').removeData('blurTimeout'); }, 100); $('body').data('blurTimeout', cucc); }); $('.result').click(function () { var cucc=$('body').data('blurTimeout'); if (typeof cucc != 'undefined') { clearTimeout(cucc); } }); 

jsFiddle Demo

+4
source

All Articles