User 4532066 User 4532066 - 3 years ago 123
HTML Question

Div appears momentarily on pageload - how do I stop it doing so?

I have a simple bit of HTML:

<input type="text" id="lk" />
<div id="showDiv">
<input type="radio" name="lki" id="lki1" value="lki1"> <label for="lki1">Anywhere</label>
<input type="radio" name="lki" id="lki2" value="lki2"> <label for="lki2">Start</label>
</div>


And this JS:

// page load
$(document).ready(function () {
var bla = $('#lk').val();
if(bla.length > 0){
$('#showDiv').show();
}
else {
$('#showDiv').hide();
}
});

// show / hide the "showDiv" content when a user types into the #lk text input field
$('#lk').bind('keyup change',function(){
if(this.value.length > 0){
$('#showDiv').show();
}
else {
$('#showDiv').hide();
}
});


There are two parts to the JS. The first should show the `#showDiv' div if the '#lk' text input field contains data.

The second will show / hide `#showDiv' based on whether someone types data into the the '#lk' text input field.

The problem I have is with the first bit of JS, for the page load:

// page load
$(document).ready(function () {
var bla = $('#lk').val();
if(bla.length > 0){
$('#showDiv').show();
}
else {
$('#showDiv').hide();
}
});


When the page first loads, the radio buttons in the `#showDiv' div often momentarily appear then disappear if the '#lk' text input field is empty.

When there is content below the form, then the content appears to jump as the `#showDiv' div appears then is hidden very quickly.

Is there a better way I can use to hide the `#showDiv' div if the '#lk' text input field is empty when the page first loads?

Answer Source

I would add this CSS rule to set an initial status where the DIV isn't shown:

#showDiv {
  display: none;
}

(That will change depending on the condition in your jQuery function, but this rule will make sure that DIV won't appear for even a milisecond when the page is loaded, before the jQuery function is performed)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download