Ways to conceal a primary page section upon clicking a different tab

I am currently implementing the w3schools HOW TO - tabs feature on my website to create tabbed navigation. However, I'm running into an issue where clicking on tabs other than 'Home' still displays the 'Home' content along with the content of the selected tab. How can I hide the 'Home' div when switching to another tab so that only the content of the active tab is visible?

Here is the HTML code for my navigation menu and the JavaScript function I am using:

<script type="text/javascript" >
    function openTab(evt, tabName) {
    // Define variables
    var i, tabcontent, tablinks;

    // Hide all elements with class "tabcontent"
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
    }

    // Remove the "active" class from all elements with class "tablinks"
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }

    // Show the current tab and add the "active" class to the selected link
    document.getElementById(tabName).style.display = "block";
    evt.currentTarget.className += " active";
}
</script>
<script type="text/javascript">

</script>
<nav class="navbar navbar-inverse navbar-fixed-top">
      <div class="container-fluid">
        <div class="navbar-header">
          <a class="navbar-brand" href="#">Ben and Lukes</a>
        </div>
        <ul class="nav navbar-nav navbar-right">
          <li><a href="#intro" class="tablinks active" onclick="openTab(event, 'intro')">Home</a></li>
          <li><a href="#About" class="tablinks" onclick="openTab(event, 'About')">About Us</a></li>
          <li><a href="#Products" class="tablinks" onclick="openTab(event, 'Products')">Products</a></li> 
          <li><a href="#Contact" class="tablinks" onclick="openTab(event, 'Contact')">Contact Us</a></li> 
        </ul>
      </div>
    </nav>

Answer №1

Streamline your JavaScript

JavaScript

openTab("Home")

function openTab(tabName) {
    var i;
    var x = document.getElementsByClassName("tab");
    for (i = 0; i < x.length; i++) {
        x[i].style.display = "none";
    }
    document.getElementById(tabName).style.display = "block";
}

Here's an example of how the HTML should appear:

<link rel="stylesheet" href="http://www.w3schools.com/lib/w3.css">
<ul class="w3-navbar w3-black">
    <li><a href="#" onclick="openTab('Home')">Home</a></li>
    <li><a href="#" onclick="openTab('AboutUs')">About Us</a></li>
    <li><a href="#" onclick="openTab('Products')">Products</a></li>
    <li><a href="#" onclick="openTab('ContactUs')">Contact Us</a></li>
</ul>

<div id="Home" class="w3-container tab">
    <h2>Home</h2>
    <p>Your Content Here</p>
</div>

<div id="AboutUs" class="w3-container tab">
    <h2>About Us</h2>
    <p>Your Content Here</p> 
</div>

<div id="Products" class="w3-container tab">
    <h2>Products</h2>
    <p>Your Content Here</p>
</div>

<div id="ContactUs" class="w3-container tab">
    <h2>Contact Us</h2>
    <p>Your Content Here</p>
</div>

View the Live CODEPEN demonstration here

Answer №2

One way to accomplish this is by utilizing jQuery:

$(".otherTab").click(function(){
      $('.homeTab').hide();
      $('.otherTab').show();
});

Answer №3

To avoid using jQuery, consider implementing an alternative like the ng-switch directive in AngularJS. Simply set a default state variable on the controller, such as displayTab = 0. When a tab is clicked, update this variable to show the corresponding tab through ng-switch.

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

Experiencing difficulty when attempting to save a zip file to the C drive

I came across this code snippet on SO and decided to use it for my project. The goal is to send a simple 1.5mb zip file and save it on my C drive by making a request through Postman with the binary option enabled, sending the zip file to localhost:3012. c ...

Transforming a collection of Javascript objects into a pure Javascript array

After JSON.stringify-ing my JavaScript object, the output looks like this: [ { "item_id": null, "parent_id": "none", "depth": 0, "left": "1", "right": 4 }, { "item_id": "1", "parent_id": ...

What is the best way to establish a new JavaScript data type that can be accessed using both key and index?

Looking to create a unique datatype or object in JavaScript that allows access by both index and key, as well as having a length property to display the number of items in the datatype. Something along the lines of: MyDataType[0].name="John" MyDataType[0 ...

Scroll horizontally through a dynamically sized div with fluid width using jQuery, pause at the beginning and end, and retrieve the width of the

It seems like what I really need is a customized jquery slider, as the ones I've experimented with (caroufredsel, elastislide, smoothdivscroll) don't quite meet my requirements. Many of them come with unnecessary extra features that I don't ...

Identify if a process operates synchronously or asynchronously

Can you identify in node.js, with the help of a function, if a method is synchronous or asynchronous? I am interested in creating a function that achieves the following: function isSynchronous(methodName) { //check if the method is synchronous, then ...

Implementing an API call in Vue JS on the app.vue component of a single page application

My project is experiencing delays in API requests due to a large amount of data. I have tried adding a cache, but the page still appears white upon creation. I am considering moving the API call to app.vue to speed up the request. Is there a way to do this ...

Is there a way to verify HTML binding prior to setting up an AngularJS directive?

On a page where I utilized a custom select-box directive to display the Month, certain arguments are required by the directive: <custom-select-box id="month" model="month" model-required model-name="month" options="month.value ...

Resetting CSS attributes in Kendo UI Mobile when transitioning between views after removing them with jQuery

Dealing with the flicker of unstyled content in my kendo mobile web app has been a challenge, but I found a solution by using a specific CSS rule within my stylesheet: [data-role="content"] { visibility: hidden; } This effectively hides all ...

Show the content of a list from a different URL on a webpage using HTML with the

My current task involves retrieving JSON data using Jquery and then displaying the names in a simple HTML list. Typically, the JSON files I work with have a straightforward format like: [ {a:1,b:2},{a:3,b:4}] However, this time, the JSON file is hosted ...

The react-xml-parser package is asking for Babel version "^7.0.0-0", however it was instead loaded with version "6.26.3". I have already attempted all available solutions to resolve this issue

I have attempted numerous solutions from the Github community regarding this issue, but unfortunately none have worked for me. /node_modules/react-xml-parser/dist/bundle.js: Requires Babel "^7.0.0-0", but was loaded with "6.26.3". If you are sure you ha ...

As the page is scrolled upwards, the custom cursor's location shifts accordingly

In developing a custom hover cursor for my video div, I am encountering an issue where the cursor does not move with my mouse and remains in place when I scroll. Could someone please review my code and identify what I am doing wrong? Additionally, I have ...

Create a line break in an alert using PHP

<?php function alert($msg) { echo "<script type='text/javascript'>alert('$msg');</script>"; } if(array_key_exists('btnRegisterAdmins', $_POST)) { $fname = $_POST['FirstName']; $lname=$_POST['La ...

What is the process for integrating three.js code manually into an iframe?

I recently posted a question on Stack Overflow inquiring about how to input code into an iframe without using a file or URL. While I was successful with simple cases like <h1>Hello World</h1>, my ultimate goal is to integrate three.js into thes ...

Struggling to figure out the correct method for aligning calendar using bootstrap-datetimepicker?

Struggling with aligning the calendar correctly under a textbox while using bootstrap-datetimepicker in a form? The positioning seems off, and the calendar icon isn't where it should be. It's not behaving like a simple datetimepicker as shown in ...

Error: Angular does not recognize x2js XML format

I'm attempting to adapt this particular example to utilize xml as json data. However, I am encountering some issues with the code. courses = x2js.xml_str2json(data); console.log(courses.books.course); $scope.todos = courses.books.course; In the XML ...

Is there a method I can use to transform this PHP script so that I can incorporate it in .JS with Ajax?

I have a JavaScript file hosted on domain1.com, but in order for it to function properly, I need to include some PHP code at the beginning. This is necessary to bypass certain restrictions on Safari for my script by creating a session. The PHP code establi ...

Exploring the functionality of $scope.$watch in ES6

I'm encountering a problem while utilizing $scope.$watch in my ES6 project. The watch triggers once and then doesn't work thereafter. Below is the snippet of code: export class SomeController { constructor($log, $scope) { 'ngInject&a ...

Looking for help combining HTML5 Canvas and JavaScript to showcase images. Can anyone lend a hand?

I am currently in the process of developing an Android game using HTML5 and Javascript. I have managed to make some progress, but I have encountered a problem that has left me puzzled. Initially, my JS file and Html file were functioning well together for ...

Utilize CSS in the same way as the legend tag styling

I'm looking to create a stylish border around my HTML component. While I know the HTML legend element can achieve this, I want to use it outside of a form. For reference on using HTML Legend: http://www.w3schools.com/tags/tryit.asp?filename=tryhtml ...

What are the advantages of importing CSS files from JS source code with webpack, rather than building CSS in isolation as traditionally done?

If you're looking for information on how to load CSS with webpack, check out the documentation here: https://webpack.js.org/guides/asset-management/#loading-css1 The webpack documentation suggests importing CSS files from JavaScript code and using ex ...