Daniel Furtado Daniel Furtado - 1 year ago 65
Javascript Question

Why does the position of the element change when I use .style.display = "block"?

I am testing my code on Firefox Ver 47 on W7

I have a two inputs for Hours and Minutes, side by side. As below,

Click to view image showing inputs side by side

The inputs and buttons are defined as follows

<input style="color: green; width: 50px; height: 17px; background-color: lightgrey; " type='number' id="hour1" value="22" min="0" max="23">
<input style="color: green; width: 50px; height: 17px; background-color: lightgrey; " type='number' id="min1" value="40" min="0" max="59"> <br>
<input type='button' value="Show custom time" onclick="show()">
<input type='button' value="Hide Custom time" onclick="hide()">

Now, when I click on 'Show custom time' button, both of the elements get aligned to the left one below the other (I do not want this to happen).

Click here to view image showing inputs position shifted

The show() and hide() functions execute as below when triggered.

function show()
document.getElementById('hour1').style.display = "block";
document.getElementById('min1').style.display = "block";
function hide()
document.getElementById('hour1').style.display = "none";
document.getElementById('min1').style.display = "none";

I have partly fixed this by introducing CSS

#hour1 {position:fixed; top:5px; left:5px;}
#min1 {position:fixed; top:5px; left:70px;}

gives an undesired floating effect.

Question is why is the position changing when I am only modifying the display property and how to workaround/fix this or am I doing something wrong?

If it helps, tried searching online and came across a scenario where
style.display = "block";
changes the sizing of the table. This was overcome by using
style.display = "table";

Answer Source

Try setting display: inline-block; instead of display: block;. This should allow the elements to flow as if they were text, but retain their block-like properties.

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