Javascript blur-click not working together

I have the following code :

HTML:

<input type='text' class='a' /> <div class='inst' tag='a'></div> <input type='text' class='b' /> <div class='inst' tag='b'></div> <input type='text' class='c' /> <div class='inst' tag='c'></div> 

JS:

 $(function() { $('.inst').click(function() { alert($(this).attr('tag') + ' clicked'); }); $('[type=text]').focus(function() { show_inst($(this).attr('class')); }).blur(function() { //hide_inst($(this).attr('class')); }); function show_inst(tag) { $('div.inst[tag=' + tag + ']').html(tag + ' instructions'); } function hide_inst(tag) { $('div.inst[tag=' + tag + ']').html(''); } }); 

CSS

 .inst { width: 200px; height: 100px; border: 1px solid black; margin: 10px; cursor: pointer; } 

It works fine: when I press inst I see a warning message, and when the input becomes focused, an instruction appears.

Now I want the inappropriate instruction to disappear on blurring. So I tried adding a commented line inside blur() . This does not work like that because blur() is called first and deletes the instruction, so if I click on the instruction nothing happens.

How can i solve this?

+2
javascript html click onblur
source share
2 answers

If your only problem is that the instruction is hidden before you click on it, you can add a little delay. This will cause your hide statement to be executed after the click has been processed.

Something like that:

 $('[type=text]').focus(function() { show_inst($(this).attr('class')); }).blur(function() { setTimeout(function(){ hide_inst($(this).attr('class')); }, 50); // make this happen after any other events }); 
+3
source share
  var timeoutId; $('[type=text]').on("blur", function(){ timeoutId = setTimeout(function(){ console.log("blur"); }, 50); }).on("focus", function(){ clearTimeout(timeoutId); }); 

Or you can try this, it will be blurred only when you leave the input (clicking β€œfalse” removes clearTimeout).

+1
source share

All Articles