HTML TABS: Make the first TAB automatically selected

I've been experimenting with tabbing in HTML using a tutorial I found on W3SCHOOLS.

While the source code provided works fine, I'm encountering an issue with automatically selecting the first tab by default. The tutorial doesn't cover this, so I'm looking for a solution to have the first tab be automatically selected and displayed when the page loads.

<!DOCTYPE html>
<html>
<style>
body {font-family: "Lato", sans-serif;}
...

<p>I've tried adding the following line inside the JavaScript for loop but it didn't work:</p>

<pre><code>tablinks[0].className += " active";

Answer №1

In the first LI tag, include class=active, and in the subsequent one, update the div with the following:

div id=London class=tabcontent style=display:block

To see a working example, check out this JSfiddle

Answer №2

If you prefer using only javascript, you can achieve this by including the following code in your script:

document.getElementsByClassName('tablinks')[0].click()

This code will simulate a click event on the first tab when the page is loaded.

Answer №3

<!DOCTYPE html>
<html>
<style>
body {font-family: "Lato", sans-serif;}

ul.tab {
    list-style-type: none;
    margin: 0;
    padding: 0;
    overflow: hidden;
    border: 1px solid #ccc;
    background-color: #f1f1f1;
}

/* Float the list items side by side */
ul.tab li {float: left;}

/* Style the links inside the list items */
ul.tab li a {
    display: inline-block;
    color: black;
    text-align: center;
    padding: 14px 16px;
    text-decoration: none;
    transition: 0.3s;
    font-size: 17px;
}

/* Change background color of links on hover */
ul.tab li a:hover {
    background-color: #ddd;
}

/* Create an active/current tablink class */
ul.tab li a:focus, .active {
    background-color: #ccc;
}

/* Style the tab content */
.tabcontent {
    display: none;
    padding: 6px 12px;
    -webkit-animation: fadeEffect 1s;
    animation: fadeEffect 1s;
}

@-webkit-keyframes fadeEffect {
    from {opacity: 0;}
    to {opacity: 1;}
}

@keyframes fadeEffect {
    from {opacity: 0;}
    to {opacity: 1;}
}
</style>
<body>

<h3>Fade in Tabs</h3>

<ul class="tab">
  <li><a href="#" class="tablinks" onclick="openCity(event, 'London')">London</a></li>
  <li><a href="#" class="tablinks" onclick="openCity(event, 'Paris')">Paris</a></li>
  <li><a href="#" class="tablinks" onclick="openCity(event, 'Tokyo')">Tokyo</a></li>
</ul>

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

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

<div id="Tokyo" class="TabContent">
  <h3>Tokyo</h3>
  <p>Tokyo is the capital of Japan.</p>
</div>

<script>
document.getElementsByClassName('tablinks')[0].click()
function openCity(evt, cityName) {
    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 < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(cityName).style.display = "block";
    evt.currentTarget.className += " active";
}
</script>

</body>
</html>

included

document.getElementsByClassName('tablinks')[0].click()
within the script

Answer №4

Include the following CSS code:

div[class*="tabcontent"]:first-of-type {
    display: block;
}

Make sure to update the HTML markup like this:

<a href="#" class="tablinks active" onclick="openCity(event, 'London')">London</a>

Check out the demonstration here.

Alternatively, you can add an active class for the content elements as well:

/* Make the selector more specific to target content elements */
ul.tab li a:focus, ul.tab li a.active {
    background-color: #ccc;
}

/* Add this to your stylesheet */
.tabcontent.active {
    display: block;
}

/* Update the HTML markup by adding the class */
<div id="London" class="tabcontent active">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying JavaScript object values using the Object() constructor

My background is in Groovy, which has similar syntax to JavaScript. In Groovy, I can easily copy values from one map to another like this: def myMap1 = {}; def myMap2 = {}; myMap1["key1"] = "value1"; myMap1["key2"] = "value2"; myMap1["key3"] = "value3"; ...

Adjust the CSS to give <a> elements the appearance of plain text

Is it possible to style an anchor tag to appear identical to plain text? Consider the following scenario: <p> Here is some text and here is a <a class='no-link' href="http://www.example.com" >link</a></p> I have atte ...

Modify the background color of a pseudo-element's property value dynamically

How do I change the background color of my burger menu by clicking on an icon? This is the CSS code I have: :root{ --pseudo-backgroundcolor: yellow; } .menu__icon span, .menu__icon::before, .menu__icon::after{ background: va ...

Change the content of an ion-card in Ionic2 dynamically

After fetching a list of books from the backend API provider, I am presented with sample data that looks like this: { "success":true, "books":[ { "id":1000, "book_code":"CC219102", "read_status":"completed", ...

Designing a layout with one box on top and two beneath it, covering the entire page, can be achieved by following these steps

I am currently working on a project where I want to divide the screen into three sections. One section will cover half of the screen to display an image slider, and the remaining half will have two sections which is already done. However, now I need to add ...

What are the steps for encoding a value using jquery serialize?

I attempted to encode all values using the following code: encodeURIComponent($("#customer_details").serialize()); Unfortunately, it did not produce the desired results. Is there a method to retrieve all elements on a form and individually encode each v ...

Check the feature that retrieves data from a `json` file

In my util file, I have a function that imports and checks whether a given sectionUUID has a video in the JSON file. import multipleVideos from '../data/videos.json' function hasSectionMultipleVideos (sectionUUID) { return multipleVideos.vide ...

Setting a callback function as a prop for react-paginate in TypeScript: A step-by-step guide

When using react-paginate, there is a prop called onPageChange with the following type: onPageChange?(selectedItem: { selected: number }): void; After implementing it like this: const onPageChange = (selected): void => { console.log(selected); } ...

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

Managing data in React and JavaScript: Clearing fields upon successful sign up and redirecting to login page after receiving a 200 status code

Here is the code for my SignUp react function. After receiving a response of 200 upon clicking the Sign up button, I want to clear the text in all three fields and redirect the user back to the login page. I'm new to web development so any assistance ...

I'm curious as to why IPC messages from one menu item in Electron can successfully reach my window, but when sent from a different menu item, they do not seem to

I am working on a straightforward application that requires running a background process to fetch some data. I want to display a loading indicator while the data is being retrieved, but I am encountering difficulties implementing this feature. My approach ...

Press the div, excluding the button - Vue

I have a basic div that spans 100% of the width, containing a button inside. The issue I'm facing is that when I add a click event to the div, the entire div becomes clickable (including the button within it). What I want is for the whole div to be ...

Filter array to only include the most recent items with unique names (javascript)

I'm trying to retrieve the most recent result for each unique name using javascript. Is there a straightforward way to accomplish this in javascript? This question was inspired by a similar SQL post found here: Get Latest Rates For Each Distinct Rate ...

Employing VUE.js for content retrieval

Is there an issue rendering 2 messages in vue.js on the front end? <template v-for="item in items"> <span>{{ afterpayMessage }}: {{ item.price }} with AfterPay</span> </template> <script> var afterpay = new Vue({ e ...

The menu seems to be off-center

I'm struggling to center my menu/navigation bar horizontally. I can't seem to figure out what mistake I've made or what I've forgotten. Additionally, there is right padding after my last list item. How can I get rid of it? HTML <di ...

Vue.js Class-based Decorator not Transmitting Event from Child to Parent Component

I'm fairly new to working with Vue.js and I've encountered an issue with the child to parent emit functionality. Essentially, I have a Box component that contains a Search component. In the Search component, I attempted the following: @Watch("se ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

Troubleshooting Problem with Retrieving Files Using jQuery Ajax

I am attempting to use ajax to retrieve the contents of a file, but it doesn't seem to be functioning properly. I'm not sure why this is happening, as I have copied the same code from the examples on w3schools.com. $().ready(function(){ ...

Charting data with missing values in Google Charts

I have generated a line chart using php and json to load the data. The issue I am facing is that the chart displays NULL values as 0, which does not look good. My assumption is that I may be formatting the json incorrectly, and what I really need is {"v" ...

What is the process for enabling SASS line numbers using Yeoman's Grunt.js file?

Recently, I used Yeoman (1.4.5) to scaffold a new web application. Within my Gruntfile.js, I configured it as follows: ... // When requested, compile Sass to CSS and generate necessary files sass: { options: { lineNumbers:true, sourceMap: true, ...