Problems with jQuery.blur () and .focus () events

I have a form with multiple input fields. When the user clicks on an input field, a hidden div appears with some highlight for that field, they can then select an option and that value is set as the value of the field.

Currently, the way the div is hidden is when the user selects an option. This works great, but what if the user doesn't want to select an option, the div won't be removed. So my solution was to use a blur event for the input fields which would hide their div element. This way the user could fill out the form, see the hidden div, and hide it when they leave the field. This also works correctly.

The problem comes when they now want to click something from the div to be filled into the input. Since I even added blur, it even fires when the user tries to click an option in the div, effectively hiding the div a little second before the user clicks, rather than adding anything to the input field.

What would be the best way to solve this problem? I would like to have a blur event to hide the div, but there must be some kind of exception when the user wants to click inside the div that the blur event will not hide the div they are trying to click on.

Thanks for the help.

+2


source to share


4 answers


You can set a timeout on the blur event and immediately hide the "help div" only if the other is the focus input field.

Something like that:



$("#input1").focus(function() { 
      hideAllHelpers(); $("#helper1").show(); 
});

$("#input1").blur(function() { 
      window.setTimeout(function() { $("#helper1").hide(); },2000); });
});

$("#input2").focus(function() { 
      hideAllHelpers(); $("#helper2").show(); 
});

// etc...

      

Surely you could make this more versatile and it could use some fine tuning, but you get the idea ...

+7


source


Onblur, set a timeout that waits seconds before hiding the corresponding one div

. Then, onclick, clear the timeout. Here's a basic example ...



// Namespace for timer
var myPage = {
  timer: null
}

// Blur event for textbox
.blur(function() {
  myPage.timer = setTimeout(function() { 
    // Hide the div
  }, 1000);
});

// Click event for DIV
.click(function() {
  clearTimeout(myPage.timer);
  // Fill in the textbox
  $(this).hide();
});

      

0


source


I would add a tab close button right after this field. This will solve the problem of a user who does not know the secret (tabulation), perhaps not realizing that there is a way to dismiss the dialog without choosing an option.

0


source


Use the mousedown event, which fires when the user clicks the helper element, but before the blur event fires on the input element.

$('#input').blur(function () {
  $('#helper').hide();
});

$('#helper').mousedown(function () {
  console.log('This executed before the blur event');
});

      

0


source







All Articles