How to avoid losing input event after switching visivility?

I have an input that needs to keep focus, due to the requirements of the program. When using software, the input might be hidden at some point, but when it appears again, it should restore focus, but it isn't. However, if you check the associated events on the input, you can see that it hasn't actually lost the event.

This simple jsfiddle demonstrates this behavior: https://jsfiddle.net/5puu261v/

$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('#barcode').toggle()">Toggle input</button>
<input type="text" id="barcode" />
      

Run codeHide result


It would be helpful if I could fix or avoid this without binding the event again.

Edit:

Point: Why is the input not focused, after switching, when clicking on any other element (like a button that makes it visible again)?

+3


source to share


2 answers


Updated violin .

You can add .focus()

to the click event so that every time the button is clicked on the input, it will focus, for example:

$('button').click(function(){
    $('#barcode').toggle().focus();
});

      

HTML:



<button>Toggle input</button>
<input type="text" id="barcode" />

      

Hope it helps.

$('#barcode').focus()

$('#barcode').focusout(function(){
    $(this).focus();
});

$('button').click(function(){
    $('#barcode').toggle().focus();
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<button>Toggle input</button>
<input type="text" id="barcode" />
      

Run codeHide result


+1


source


You can call the method again focus

on onclick

button event:



$('#barcode').focus()

$('#barcode').focusout(function(){
  $(this).focus();
});
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="$('#barcode').toggle();$('#barcode').focus();">Toggle input</button>
<input type="text" id="barcode" />
      

Run codeHide result


0


source







All Articles