1

I wrote some simple jQuery code for a mobile website. If I touch the delete button it clears the input and focuses in an input area. However it automatically focus out after focus()

$(document).on('focusin', '#testInput', function() {
  console.log('in')
});

$(document).on('focusout', '#testInput', function() {
  console.log('out')
});

$(document).on('touchstart', '#deleteButton', function() {
  console.log('touchs')
  $('#testInput').val('').focus();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<div id="wrap">
  <div class="title">
    <span>MOBILE TEST</span>
  </div>
  <div class="content">
    <input type='text' id="testInput" name="testInput" class="input_text">
    <button id="deleteButton" type="button" class="delete_button">x</button>
  </div>
</div>
kingjakeu
  • 13
  • 2

1 Answers1

0
  1. Why You don't use the tap event? This is the standard for user interaction.

    You need to remember that it is the user interaction which is stealing the focus from the active element. There isn't any magic "event trigger" behind that. At most, the sequence order of the many touchstart, mousedown. click, tap, and so on... is browser-dependent and need some quirks to work correctly cross-browser. You should use the tap event also because, just for instance, the user should be able to leave the finger from the cancel button and nothing should happen.

  2. Besides this, if You absolutely stick with touchstart and Your button is just like a kind of graphical input and don't need a click or whatsoever event, try this and see that it will work:

    $('#deleteButton').on('touchstart', function() {
      $('#testInput').val('').focus();
      return false;
    });
    
  3. But in Your example You are using event delegation. Read this: What is DOM Event delegation?.

    So, if You need event delegation. there is also the need to stop the event bubbling:

    $(document).on('touchstart', '#deleteButton', function(e) {
      $('#testInput').val('').focus();
      return false;
    });
    $(document).on('touchend', '#deleteButton', function(e) {
      return false;
    });
    

Eventually, here is a great explanation about return false inside the jQuery event handlers:

event.preventDefault() vs. return false

deblocker
  • 7,277
  • 2
  • 18
  • 49