Search code examples
javascriptjqueryfocus

giving focus after slideDown - input changes its height


in the example below click on button and wrap will toggle
problem - the first input changes its height and it makes an aditional slideDown of entire wrap
the reason is $('#inpname').focus(); line - without it everything is ok
how to keep the focus and avoid this additional effect ?

update

I tried - without success:

$('button').on('click', async function(){
    await $('#wrap').slideToggle();
  $('#inpname').focus();
});

$('button').on('click', function(){
    $('#wrap').slideToggle();
  $('#inpname').focus();
});
.wrap{display:none;}

.inpname, .inpcontact{
    display:block;
    height:36px;
    width:90%;
    padding:0 20px;
    background:#eee;
    border-radius:25px;
    font-family:montserrat;
    font-size:1.6rem;
    font-weight:500;
    letter-spacing:1px;
    color:#333;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button>CLICK</button>
<br><br>
<div class='wrap' id='wrap'>
<input type='text' class='inpname' id='inpname' placeholder='lorem'>
<br>
<input type='text' class='inpcontact' id='inpcontact'>
<br>
</div>


Solution

  • What you can do is this:

    $('#wrap').slideToggle(function() {
      $('#inpname').focus();
    });
    

    This will run your focus after the slideToggle is done.

    Demo

    $('button').on('click', function() {
      $('#wrap').slideToggle(function() {
        $('#inpname').focus();
      });
    });
    .wrap {
      display: none;
    }
    
    .inpname,
    .inpcontact {
      display: block;
      height: 36px;
      width: 90%;
      padding: 0 20px;
      background: #eee;
      border-radius: 25px;
      font-family: montserrat;
      font-size: 1.6rem;
      font-weight: 500;
      letter-spacing: 1px;
      color: #333;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <button>CLICK</button>
    <br><br>
    <div class='wrap' id='wrap'>
      <input type='text' class='inpname' id='inpname' placeholder='lorem'>
      <br>
      <input type='text' class='inpcontact' id='inpcontact'>
      <br>
    </div>