How to Create a Dynamic Tabbed Interface with HTML, CSS, and JavaScript?

I’m trying to create a dynamic tabbed interface for my website where users can click on different tabs to display different content sections. I’ve been able to create static tabs using HTML and CSS, but I’m not sure how to make them dynamic using JavaScript.

Here’s what I have so far:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tabbed Interface</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="tabs">
        <button class="tab-link active" onclick="openTab(event, 'Tab1')">Tab 1</button>
        <button class="tab-link" onclick="openTab(event, 'Tab2')">Tab 2</button>
        <button class="tab-link" onclick="openTab(event, 'Tab3')">Tab 3</button>
    </div>
    <div id="Tab1" class="tab-content">
        <h3>Tab 1</h3>
        <p>Content for Tab 1.</p>
    </div>
    <div id="Tab2" class="tab-content" style="display:none;">
        <h3>Tab 2</h3>
        <p>Content for Tab 2.</p>
    </div>
    <div id="Tab3" class="tab-content" style="display:none;">
        <h3>Tab 3</h3>
        <p>Content for Tab 3.</p>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS:

body {
    font-family: Arial, sans-serif;
}

.tabs {
    overflow: hidden;
    background-color: #f1f1f1;
    border-bottom: 1px solid #ccc;
}

.tab-link {
    background-color: inherit;
    border: none;
    outline: none;
    cursor: pointer;
    padding: 14px 16px;
    transition: background-color 0.3s;
}

.tab-link:hover {
    background-color: #ddd;
}

.tab-link.active {
    background-color: #ccc;
}

.tab-content {
    display: none;
    padding: 6px 12px;
    border: 1px solid #ccc;
    border-top: none;
}

JavaScript:

function openTab(evt, tabName) {
    var i, tabcontent, tablinks;

    tabcontent = document.getElementsByClassName("tab-content");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    tablinks = document.getElementsByClassName("tab-link");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}

This code mostly works, but I’m running into a few issues:

  1. The default active tab doesn’t display its content until I click on another tab and then back.
  2. The CSS styles don’t seem to transition smoothly when switching tabs.

Can someone help me understand how to fix these issues or suggest a better approach to create a dynamic tabbed interface?

Thanks in advance!