J. Coderino
J. Coderino

Reputation: 209

Jquery hide/show delay fix

Hey i have 2 blocks in the same place where people can put in a number. If there is no number it hides. But i want to give them the time to change it to another number. So i delay the hiding with ms. But then they see an animation of the hiding/showing. Is there a way to fix?

$('#FenceMeters').on('input', function() {
  if($('#FenceMeters').val() != "" && Number($('#FenceMeters').val()) >=5){
     $('#testje').show();
     $('#SummaryHTML').hide();
  } else{
    $('#testje').hide(1000);
    $('#SummaryHTML').show();
  }
});

Upvotes: 1

Views: 159

Answers (1)

Oliver Trampleasure
Oliver Trampleasure

Reputation: 3293

.hide() will immediately make the element non-visible, you can add a value between the parenthesis to dictate a duration for a transition. Numerical values are in milliseconds .hide(1000), you can also use .hide(slow), .hide(fast), etc. Documentation


Starting a countdown

In order to delay the hiding of your element, you need to split your code up into two different functions. The command .setTimeout(hideTestje,1000) starts a countdown before running the hideTestje function with a countdown duration of 1000 milliseconds (1 second).

Cancelling a countdown

If the user then continues to input into the textbox, and the value meets your two conditions, then the command .clearTimeout(delayedTestjeHide) will cancel the countdown.

var delayedTestjeHide;

$('#FenceMeters').on('input', function() {
  if($('#FenceMeters').val() != "" && Number($('#FenceMeters').val()) >=5){
     $('#testje').show();
     $('#SummaryHTML').hide();
     window.clearTimeout(delayedTestjeHide);
  } else{
      delayedTestjeHide = window.setTimeout(hideTestje,1000);
  }
});


function hideTestje() {      
    $('#testje').hide();
    $('#SummaryHTML').show();
}
#testje {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="FenceMeters">
<div id="testje">testje</div>
<div id="SummaryHTML">SummaryHTML</div>

Upvotes: 1

Related Questions