MickG MickG - 7 months ago 60
CSS Question

Moving a <script> changes the result: why?

This is the code:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div style="text-align: justify">[Introduction text]</div> <br> <br>
<ul class="nav nav-tabs">
<li class="active">
<a data-toggle="tab" href="#Vspoiler" id="defaultOpen" onclick="openPage('Vspoiler')">Vulgate version</a>
</li>
<li>
<a data-toggle="tab" href="#Cspoiler" onclick="openPage('Cspoiler')">Campbell version</a>
</li>
</ul>
<div id="Vspoiler" class="tab-pane tabcontent active"><br>
<table>
<tbody>
<tr>
<td>
<div class="column" style="padding-left: 80px"> [Contents of col 1 of tab 1] </div>
</td>
<td>
<div class="column" style="padding-left: 80px"> [Contents of col 2 of tab 2] </div>
</td>
</tr>
</tbody>
</table>
</div>
<div id="Cspoiler" class="tab-pane tabcontent"><br>
<table>
<tbody>
<tr>
<td>
<div class="column" style="padding-left: 80px"> [Contents of col 1 of tab 2] </div>
</td>
<td>
<div class="column" style="padding-left: 80px"> [Contents of col 2 of tab 2] </div>
</td>
</tr>
</tbody>
</table>
</div>
<script>

function openPage(pageName) {
var i, tabcontent;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}

document.getElementById(pageName).style.display = "block";
}

document.getElementById("defaultOpen").click();

</script>


In the above code, there is a element at the end. If it is left there, the output is as desired. If moved to the top, the output changes, in that the contents of all the
tabcontents
panes (or whatever the best term to call them is) is shown upon loading, and only when an inactive tab is clicked do the contents of the others (in this case 1 but any others if there are more than 2 total) disappear. Why does that happen?

Note: This is a follow-up to this, and the code is mostly by @Bradley who answered there.

Answer Source

That's happens because the script run before document is ready. ( sync ). If you want to keep your script at the beginning of the body, or in head, use de window.onload function.

window.onload = function()
{ 
 // your code goes here
}

My suggestion will be to place the script at the end of the body, also the bootstrap and jquery libs, because those scripts will be fired after the DOM is ready.

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