Jeosiyy Chu Jeosiyy Chu - 5 months ago 34
HTML Question

How to always show the first TAB

I want to show the first tab always whenever the page load, which is the "Details" tab, any idea to do it? I have tried added JavaScript which runs on pageload, but it didn't work out as I wish.

HTML:

<ul class="tab">
<li><a href="javascript:void(0)" class="tablinks" onclick="openTab(event, 'Details')">Details</a></li>
<li><a href="javascript:void(0)" class="tablinks" onclick="openTab(event, 'Reviews')">Reviews</a></li>
</ul>

<div id="Details" class="tabcontent">
<h3>Details</h3>
<p>London is the capital city of England.</p>
</div>

<div id="Reviews" class="tabcontent">
<h3>Reviews</h3>
<p>Paris is the capital of France.</p>
</div>


JavaScript:

function getFirstChildWithTagName(evt, tagName) {
for (var i = 0; i < element.childNodes.length; i++) {
if (element.childNodes[i].nodeName == tagName) return element.childNodes[i];
}
}

function openTab(evt, tabName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tabcontent.length; i++) {
tablinks[i].classList.remove("active");
}
document.getElementById(tabName).style.display = "block";
evt.currentTarget.classList.add("active");
}

$(document).ready(function () {
$('.tablinks:first').addClass('active');
});


Tried the following code, but it didn't work:

function LoadFunction() {
var mybtn = document.getElementsByClassName("tablinks")[0];
mybtn.click();
}
window.onload = LoadFunction();

Answer

One approach is to add style elements that mimic button click in the initial HTML.

Add active class to tablink button

<li><a href="javascript:void(0)" class="tablinks active" onclick="openTab(event, 'Details')">Details</a></li>

Add display style to tab content

<div id="Details" class="tabcontent" style="display:block">

Hope that helps