Displaying default tab content while hiding other tab content in Javascript can be achieved through a simple code implementation

I have designed tabs using the <button> element and enclosed the tab content within separate <div></div> tags like shown below:

function displayTab(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 < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";                
}
<button class="tablinks" onclick="displayTab(event, 'Tab1')">Tab1</button>
<button class="tablinks" onclick="displayTab(event, 'Tab2')">Tab2</button>

<div id="Tab1" class="tabcontent">
    <h5>Title</h5>
    <div class="a">
        <p>Content</p>
    </div>
</div>

By default, all contents are initially hidden. In order to display Tab1 by default, how can I modify the script?

Answer №1

    <div id="Tab1" style="display: block;" class="tabcontent">
        <h5>Header</h5>
        <div class="a">
            <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
        </div>
    </div>
    <div id="Tab2" style="display: none;" class="tabcontent">
        <h5>Header 2</h5>
        <div class="a">
            <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p>
        </div>
    </div>

If you decide to add additional tabs, remember to maintain their style as display: none with only Tab1 set to display:block.

Answer №2

Utilize the bootstrap tab feature, ensuring that the first tab is always active by setting it as class="active" for easy maintenance. Check out this link to learn more about using bootstrap tabs: here

In addition, your code appears to be fine. Simply show or hide tabs based on the onclick event to display or conceal the desired tab easily.

Answer №3

function toggleTab(val) {
  if ($("#" + val).hasClass("ActivTab")) {
    $("#" + val).removeClass("ActivTab").addClass("deactivTab")
  } else {
    $("#" + val).addClass("ActivTab").removeClass("deactivTab")
  }
}
.ActivTab {
  display: block
}

.deactivTab {
  display: none
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button class="tablinks" onclick="toggleTab('Tab1')">Tab1</button>
<button class="tablinks" onclick="toggleTab('Tab2')">Tab2</button>

<div id="Tab1" class="tabcontent ActivTab">
  <h5>Title</h5>
  <div class="a">
    <p>Content</p>
  </div>
</div>
<div id="Tab2" class="tabcontent deactivTab">
  <h5>Title2</h5>
  <div class="a">
    <p>Content</p>
  </div>
</div>

Answer №4

HTML: Make sure to assign the '.open' class to your initial tab.

CSS:


.tabcontent {
display: none;
}

.tabcontent.open {
display: block;
}

JavaScript: Create a click event that will handle toggling the '.open' class. When clicked, remove the '.open' class from any existing '.tabcontent.open' element and add it to the clicked tab. All within the same click snippet.

Simple, right?

Answer №5

Utilize this code to display data upon clicking any tab. Simply replace your existing JavaScript code with the corrected one provided below.

function showData(event, toolName) {

  var i, tabsContent, tabsLinks;

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

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

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

tabsContent = document.getElementsByClassName("tabcontent");
for (i = 1; i < tabsContent.length; i++) {
  tabsContent[i].style.display = "none";
}

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

Having difficulty with CSS animation and background issues

I can't seem to get my rotating background to work using CSS keyframe animation. I've tried different things but can't figure out what's going wrong. Below is my code: .main-header { width: 100%; Height: 128px; } .main-header, ...

Is there a way to set the starting position of the overflow scroll to the middle?

Is there a way to have the overflow-x scrollbar scroll position start in the middle rather than on the left side? Currently, it always begins at the left side. Here is what it looks like now: https://i.stack.imgur.com/NN5Ty.png If anyone knows of a soluti ...

What is the best way to connect an external CSS file to an HTML file in Pycharm?

Within the project directory, I've placed both the HTML and CSS files in the 'venv' library root folder. The HTML file is named index.html The CSS file is named styles.css This is the code snippet I used to link the CSS: <link rel=" ...

Call a PHP function within a functions file using a JavaScript function

Seeking a way to navigate between PHP and JavaScript worlds with confidence. There's a collection of PHP functions stored neatly in custom_functions.php waiting to be called from JavaScript. As I delve into the realm of JavaScript and jQuery, my fam ...

Adjustable div with varying positions and dimensions

Hey there! I'm currently working on creating a page with a variable number of resizable divs. These divs can be resized horizontally using Bootstrap's col classes (col-2 through col-12), and vertically with no limits. Additionally, new divs can b ...

Passing data to a server-side component in Next.js: a guide

I am working on a website dedicated to dynamic blogs and I need to pass parameters to an API URL in order to retrieve a specific blog. However, I must ensure that the approach I take does not hinder SEO by utilizing local storage, cookies, or any other c ...

Tips for displaying dynamic images using the combination of the base URL and file name in an *ngFor loop

I have a base URL which is http://www.example.com, and the file names are coming from an API stored in the dataSource array as shown below: [ { "bid": "2", "bnam": "ChickenChilli", "adds": "nsnnsnw, nnsnsnsn", "pdap": " ...

Is there a way to include the request body (req.body) in the msg object using express-winston?

My current challenge involves logging {{ req.body }} using the msg: object in express-winston. Even after whitelisting the body with expressWinston.requestWhitelist.push('body');, it still does not appear in the log. export const accessLogger = ...

Updating the angular $resource method

I need to customize the query()-method of AngularJS $resource by using a custom $http-GET. However, it doesn't seem to be overriding the operation correctly. The result I am getting is an object with method, data, and headers, instead of data.rows[]. ...

The choice between using inline style objects with React or utilizing traditional CSS classes presents distinct advantages and

Is there a discernible difference between utilizing an inline style object for react components and using a normal CSS class through the className attribute? Even when wanting to modify styles based on a specific event, simply changing the className should ...

Creating a merged object from a split string array in TypeScript

I possess an array containing objects structured as follows; const arr1 = [ {"name": "System.Level" }, {"name": "System.Status" }, {"name": "System.Status:*" }, {"name": "System.Status:Rejected" }, {"name": "System.Status:Updated" } ] My object ...

Using `reduce` in TypeScript, you can organize an array of objects based on a shared property

Here is an example of an array: [ { id: '1', task: 'Grocery shopping', isImportant: true }, { id: '2', task: 'Meeting', isImportant: false }, { id: '3', task: &apos ...

Unable to access property within JSON object sent via POST request

I encountered an issue TypeError: Cannot read property &#39;tasks&#39; of undefined While attempting a new POST request on my API, here is the request body I am using: { "name": "example1", "description": "teaching example1", "rules" ...

Using Material-UI to implement a Link component from the react-router library

I'm having trouble integrating the <Link/> component into my material-ui AppBar. Here is my navigation class: class Navigation extends Component { constructor(props) { super(props) } render() { var styles = { appBar: { ...

Issue: Module 'blog' not found in the specified path in my Node.js application

this snippet showcases my code in routes/blog.js var express = require('express'); var router = express.Router(); const Blogs = require("../models/blog"); and here is the code from models/blog.js const mongoose = require('mongoose ...

Layer divs on top of each other without explicitly defining their stacking order

I am looking to stack multiple tile divs on top of each other by using negative margin-right: -10px. My goal is to have the previous div displayed on top, with new sibling divs appearing below it. Currently, the newer div overlaps the previous one. While ...

Leveraging the power of Auth0 and Prisma in aggregating user data

In my current project, I am developing a Next.js application with Auth0 as the authentication system. Users are authenticated using the standard middleware: import { withMiddlewareAuthRequired } from '@auth0/nextjs-auth0/edge'; export default wi ...

Tips for correctly mentioning a user while using message.channel.send in discord.js

Looking for guidance on tagging a user properly using message.channel.send in discord.js? Here's the code I'm currently working with: function replaceAll(str, find, replacer) { return str.replace(new RegExp(find, 'g'), replacer) ...

What is the best method of transferring all procedures from frida javascript rpc.exports to python?

I have a JavaScript file containing rpc.exports rpc.exports = { callfunctionsecret: callSecretFun, callfunctionsomethingelse: callSomethingElse, } I am trying to retrieve a list of all these functions in Python, but I have been unable to find a so ...

The jQuery prop method seems to be malfunctioning

Here is the HTML code snippet: <ul class="expander-list" id="category"> <li> <div class="radio" style="padding-left:0px"> <label> <input type="checkbox" id="all" ...