Concealing Website Elements with javascript based on class assignments

Despite my hesitation, I have to ask this question after unsuccessful searches in related articles. In my code, I have 7 nav links all with the same class. Due to the length of the HTML, I am looking for a way to hide contents until the link is clicked, and then have the content disappear when another nav link is clicked to make space for the next one. I would appreciate an answer in vanilla js, as that is what I am currently learning. You can find my pen here.


     <ul>
    <a href="#Hello_World" class="nav-link" onclick='myFunction()'>
        <li>Hello World</li>
    </a>
    <a href="#Introducing_JSX" class="nav-link">
        <li>Introducing JSX</li>
    </a>
    <a href="#Rendering_Elements" class="nav-link">
        <li>Rendering Elements</li>
    </a>
    <a href="#Components_and_Props" class="nav-link">
        <li>Components and Props</li>
    </a>
    <a href="#State_and_Lifecycle" class="nav-link">
        <li>State and Lifecycle</li>
    </a>
    <a href="#Handling_Events" class="nav-link">
        <li>Handling Events</li>
    </a>
    <a href="#Thinking_in_React" class="nav-link">
        <li>Thinking in React</li>
    </a>
    
    </ul>

This is how my navigation bar looks like.

Please note that I am new to JavaScript. Thank you for your understanding and time.

Answer №1

I am following along with this helpful tutorial.

Styling with CSS:

.tabcontent{display:none}

Building the Structure in HTML:

<ul>
    <li>
        <button id="default" class="tablinks" onclick="myFunction('helloWorld')">Hello World</button>
        <div id="helloWorld" class="tabcontent">
            <ul><li>1</li><li>2</li><li>3</li></ul>
        </div>
    </li>
    <li>
        <button class="tablinks" onclick="myFunction('jsx')">JSX</button>
        <div id="jsx" class="tabcontent">
            <ul><li>Intro JSX</li><li>Intro JSX 2</li></ul>
        </div>
    </li>
    <li>
        <button class="tablinks" onclick="myFunction('react')">React</button>
        <div id="react" class="tabcontent">
            <ul><li>intro raect 1</li><li>intro react 2</li></ul>
        </div>
    </li>
</ul>

Implementing JavaScript Functionality:

function myFunction(id){
    var i, tabcontent;

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

    // Display the current tab and add an "active" class to the corresponding button
    document.getElementById(id).style.display = "block";
}

document.getElementById("default").click();

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

I am attempting to display only the description of the button that I click on

How can I ensure that only the container pressed will display its description when the description button is clicked, instead of all mapped containers showing their descriptions? `import { useState } from "react"; export default function Se ...

Clear backdrop with solid objects

I am trying to achieve a unique design where the body has an image background, and the main div has a semitransparent background. I want the image to be visible through the main div, but in a shaded manner. However, the traditional approach may cause every ...

Uninterrupted Horizontal Text Scrolling using Pure CSS

I am currently working on developing a news ticker that displays horizontal text in a continuous scrolling manner, without any breaks between loops. While I hope to achieve this using only CSS and HTML, I'm unsure if it's feasible. Here is my ini ...

Harnessing the Power of NextJS Image Component and @svgr/webpack for Seamless Integration

I have recently set up a Next.js site utilizing the @svgr/webpack library. In order to start using an SVG image with the new next/image component, I configured my next.config.js file accordingly. My next.config.js setup looks like this: module.exports = { ...

The request body parser for the express POST method appears to be devoid of

After encountering similar issues on Stack Overflow, I discovered a solution involving the use of: app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); However, despite implementing this solution, the log for req.body is still ...

attempting to eliminate on-screen buttons by hovering over the video

Is there a way to make my video play on loop like a GIF without the controls ever showing? I want it to have a seamless playback experience. Any ideas would be appreciated. P.s. Don't worry about any StackOverflow errors when running the snippet. Than ...

Quick method to populate an array with elements

I need to populate an array with a large number of objects. Currently, my approach looks like this: let useVertices = []; const len = this.indices.length; for(let i = 0; i < len; i++){ let index = this.indices[i]*3; useVertices.push(new THREE.Ve ...

Is it possible for PHP to dynamically load a file based on a condition set in JavaScript?

I am attempting to dynamically insert a PHP include onto the page once the user scrolls to a specific part of the page. Is this feasible? For example: var hasReachedPoint = false; $(window).scroll(function() { var $this = $(this); if ($this.scrollTo ...

Nested loop combining Callback and Promise with two API requests

I apologize for the lackluster title, but I couldn't come up with anything more suitable. If this issue has already been addressed, please let me know in the comments and I will delete it promptly. However, keep in mind that this is a specific questio ...

Ways to implement form validation with JavaScript

I'm currently working on a project for my digital class and I'm facing an issue with my booking form. I have two functions that need to execute when a button is clicked - one function validates the form to ensure all necessary fields are filled o ...

Issues with routing in NodeJS Express causing routes to not be called

I've been working on setting up a basic REST API using nodeJS. However, I am facing an issue where none of the endpoints are being called when I try to access them. Can someone guide me on what changes I need to make in order to get it working properl ...

Managing a database update when server actions involve various form types

My UI dashboard contains multiple forms like "edit title" and "edit description", each with just one input element. I am looking to streamline database updates and server actions in next js 14, utilizing useFormState on the front end. While I have achieve ...

Concealing the sidebar in React with the help of Ant Design

I want to create a sidebar that can be hidden by clicking an icon in the navigation bar without using classes. Although I may be approaching this incorrectly, I prefer to keep it simple. The error message I encountered is: (property) collapsed: boolean ...

Continue iterating using (forEach, map,...) until the object (children) has no more elements

I need to disable the active status for all elements within my object structure. Here is an example of my object: const obj = { name: 'obj1' , ative: true , children: [ { name: 'obj2' , ative: true , children: ...

Expanding Images with JQuery Accordion

I'm facing a problem where I need to include accordions on my website with images, but whenever the accordion is opened, the image ends up stretched. Is there a solution to prevent this from happening? Below is the code snippet I am using: [Fiddle] ...

Enhance the HTML content using a JavaScript function

Here is the code that I have: <label>Brand</label></br> <select name="brand" id="brand" onChange="changecat(this.value);"> <option value="" selected>Select Brand</option> <option value="A">AMD</option&g ...

Unusual "visual" phenomenon with autocomplete feature in VUE.js

Can someone review this code snippet? Check out the code here This is a peculiar example of a custom autocomplete VUE component. If you enter a value in one of the fields in Section 1 (like 'Apple'), then click on the Next button, you'll ...

Issue with unordered list in the footer overlapping other elements

I've been struggling to resolve an issue with my footer for quite some time now. The problem seems to be arising from my unordered list being set to float right, causing it to overflow the parent div. Could someone please shed light on what I might b ...

Ensure that clicking on an element closes any currently visible elements before opening a new element

Take a look at my code snippet below. I am working on creating multiple clickable divs that reveal different content when clicked. However, the issue I am facing is that currently, both content blocks can be displayed simultaneously. My goal is to have onl ...

Typehead.js on Twitter is displaying the full query instead of just the value

The Problem This is the issue I am facing with my code. My goal is to retrieve only the value, but instead of that, the entire query value is being returned. var engine; engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue&apo ...