What is the best way to display the tabcontent when clicking on a menu tab in this code, as neither method seems to work?

Take a look at my JSFiddle demo:

<http://jsfiddle.net/xrtk9enc/2/>

I suspect that the issue lies within the javascript section. My html code includes an Unordered List that serves as the tab menu. Each href of the menu corresponds to a tab content, where I want to make sure that if the div has the .tabactive class, it is displayed (display: block), while the other 3 divs are set to 'display: none' in the CSS.

I've been struggling with this for a week and can't seem to figure out the solution. Is there anyone out there who can offer some assistance?

Edit:

Quick note, I'd prefer not to utilize jQuery for this.

Answer №1

Using Jquery to create tab functionality

$("ul.tab-links li").each(function() {
  $(this).click(function(){
    var tab = $(this).data('tab');
    $("ul.tab-links").find('li').removeClass("active");
    $(this).addClass('active');
    $(".tab-content").find('[id^=tab]').removeClass("tabactive").addClass('tab');
    $(".tab-content").find('#tab' + tab).removeClass("tab").addClass("tabactive");
  });
});
body {
background-color: blue;    
}

.tabs {
    width:100%;
    display:inline-block;
}
 
    /*----- Tab Links -----*/
    /* Clearfix */
    .tab-links:after {
        display:block;
        clear:both;
        content:'';
    }
 
    .tab-links li {
        margin:0px 5px;
        float:left;
        list-style:none;
    }
 
        .tab-links a {
            padding:9px 15px;
            display:inline-block;
            border-radius:3px 3px 0px 0px;
            background:#7FB5DA;
            font-size:16px;
            font-weight:600;
            color:#4c4c4c;
            transition:all linear 0.15s;
        }
 
        .tab-links a:hover {
            background:#a7cce5;
            text-decoration:none;
        }
 
    li.active a, li.active a:hover {
        background:#fff;
        color:#4c4c4c;
    }
 
    /*----- Content of Tabs -----*/
    .tab-content {
        padding:15px;
        border-radius:3px;
        box-shadow:-1px 1px 1px rgba(0,0,0,0.15);
        background:#fff;
    }
 
        .tab {
            display:none;
        }
 
        .tabactive{
            display:block;
        }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<link rel='stylesheet' href='style.css' type="text/css"/>
<script src='script.js' type="text/javascript"></script>
<body>
<div class="tabs">
<ul class="tab-links">
   <li class="active" data-tab="1"><a href="#tab1">Tab #1</a></li>
    <li data-tab="2"><a href="#tab2">Tab #2</a></li>
    <li data-tab="3"><a href="#tab3">Tab #3</a></li>
    <li data-tab="4"><a href="#tab4">Tab #4</a></li>
</ul>
 
    <div class="tab-content">
        <div id="tab1" class="tabactive">
            <p>Tab #1 content goes here!</p>
            <p>lol</p>
        </div>
 
        <div id="tab2" class="tab">
            <p>Tab #2 content goes here!</p>
            <p></p>
        </div>
 
        <div id="tab3" class="tab">
            <p>Tab #3 content goes here!</p>
            <p>lol</p>
        </div>
 
        <div id="tab4" class="tab">
            <p>Tab #4 content goes here!</p>
            <p>lol</p>
        </div>
    </div>
</div>
</body>

Answer №2

Upon reviewing your code, I have identified three main issues that need to be addressed.

  1. It seems that jsfiddle does not support the use of the onclick attribute. I encountered difficulties in getting it to work properly. Converting your code into an HTML document resolved this issue.
  2. The
    removeAttribute('class', 'tabactive');
    method was returning undefined and causing the code to break. It would be better to simply change the element to the tab class rather than removing it entirely.
  3. There was a missing parameter in the tabclick function when it was called in the onclick attribute. I have modified the function so that it now returns the id of the tab div that you want to display.

Here is the updated tabClick function:

function tabClick(tab, tabContent) {
    var newcontent=document.getElementById(tabContent);
    document.getElementsByClassName('active')[0].removeAttribute('class', 'active');
    tab.setAttribute('class', 'active');
    document.getElementsByClassName('tabactive')[0].setAttribute('class', 'tab');
    newcontent.setAttribute('class', 'tabactive');
}

Here is the revised HTML:

<div class="tabs">
<ul class="tab-links">
   <li class="active" onclick="javascript:tabClick(this,'tab1')"><a href="#tab1">Tab #1</a></li>
    <li onclick="javascript:tabClick(this,'tab2')"><a href="#tab2">Tab #2</a></li>
    <li onclick="javascript:tabClick(this,'tab3')"><a href="#tab3">Tab #3</a></li>
    <li onclick="javascript:tabClick(this,'tab4')" ><a href="#tab4">Tab #4</a></li>
</ul>

<div class="tab-content">
    <div id="tab1" class="tabactive">
        <p>Tab #1 content goes here!</p>
        <p>lol</p>
    </div>

    <div id="tab2" class="tab">
        <p>Tab #2 content goes here!</p>
        <p></p>
    </div>

    <div id="tab3" class="tab">
        <p>Tab #3 content goes here!</p>
        <p>lol</p>
    </div>

    <div id="tab4" class="tab">
        <p>Tab #4 content goes here!</p>
        <p>lol</p>
    </div>
</div>

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

Identify the changed field using Javascript

In my MVC application, I have a form with multiple fields that I am monitoring for changes using JavaScript. The code snippet below keeps track of any changes made in the form: var _changesMade = false; // Flag the model as changed when any other fie ...

Exploring Hover Effects in Reactjs and Material UI

I've been working with reactjs and material ui, but I'm having trouble changing the background color of selected items in various components, like in the SelectField. <SelectField floatingLabelText="Choose a sport" value={this.state.val ...

The grpc client is not able to receive the data being streamed from the

I've been attempting to stream the output of a nodejs child process through grpc, but I consistently receive an empty result. Here is my proto file: syntax = "proto3"; package servicePackage; service Mobile { rpc sign(Empty) returns ( ...

Managing JSON data through AJAX in ColdFusion

For my external API call using AJAX, I am incorporating a local API setup as an intermediate step. The process is as follows: The Ajax call sends data to localAPI.cfm. Within localAPI.cfm, there is a <cfhttp> tag to forward the data to an external ...

The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows: @NgModule({ declarations: [ PressComponent, LegalComponent, InviteComponent ], providers: [ AuthService ], imports: ...

What are some ways to utilize JavaScript for expanding an HTML form?

I am in the process of developing a basic web application that allows users to create messages with attached files. multiple html file inputs using this javascript link: http://img38.imageshack.us/img38/4474/attachments.gif The functionality to "attach a ...

Display the text area when the "Yes" radio button is clicked, while it remains hidden either by default or when the "No" radio button is selected

I am currently working on an html code and I am looking for a way to use java script in order to create a text area box only when the "Yes" radio button is selected. This text area should be hidden by default or when selecting "NO". <table class="tab ...

Omit child DIV element in JavaScript and the Document Object Model

I have a situation with two div elements. One is <div class="card" id="openWebsite"> and the other is a sub-division <div class="card__btn"> Here's the issue: When someone clicks on the main div, they get red ...

What is the best way to invoke a function in Typescript while retrieving data?

Is it possible to run a query in my main.ts file with another ts file and then pull the result of the query into another file? If so, how can this be achieved? Here is an example from my main.ts file: async function getAllTips() { const tips: any = []; ...

Navigate through JSON data to uncover the tree structure path

In my project, I am working on creating a treeview user interface using the JSON provided below. I have included properties such as node-id and parentId to keep track of the current expanded structure. Next, I am considering adding a breadcrumb UI compone ...

conceal the .card-body element if the children have the CSS property "display:none"

My challenge involves managing two collapsible cards on a webpage. I am looking for a solution where the .card-body will have its display set to none when there are no inner divs to show in the card upon clicking a letter in the pagination. Otherwise, the ...

Spin the Three.js camera in a circular motion along the Y-axis

I'm feeling a bit puzzled about this one :S I've written a code that allows my camera to rotate only halfway. I can move the camera along half of a circle using mousemove events, but I actually want it to be able to complete a full rotation :) ...

Numerous entities in motion, each adorned with its own accompanying text

I have been experimenting with the interactive cubes and recently implemented a click function that directs to specific links. Now, I am interested in assigning distinct text to each cube as a material when rendered. Currently, I am using a single materi ...

Structure of Sequelize calls

Recently, I've been working with sequelize and attempting to query my database with the code below: models.user.findOne({ where: {email: req.body.email} }, (err, existingUser) => { .... More code } Unfortunately, the code block isn't executi ...

The variable X has been defined, but it's never actually utilized. Despite declaring it, I have not accessed its

I have encountered warnings in VSCode while using certain properties in my Angular component. The warnings state: '_id' is declared but its value is never read.ts(6133) (property) ItemEditComponent._id: number | undefined '_isModeEdit' ...

Using local file paths in v-lazy-image does not function properly

When trying to use the v-lazy-image plugin for my page banner with local image files, it does not seem to work. <v-lazy-image srcset="../../../assets/images/banners/Small-Banner.svg 320w, ../../../assets/images/banners/Big-Banner.svg 480w&quo ...

Issue occurs when using Angular Firebase $createUser method

I'm stuck on this issue. I'm attempting to set up a user with AngularFire using $firebaseAuth instead of the deprecated FirebaseSimpleLogin, as advised in the documentation. I am confident that the form is submitting a valid email and password, b ...

Is the data set in stone, or is it just the API data that can

Recently, I embarked on the journey of creating a blog using nextjs, MongoDB, and express. Taking advantage of getStaticProps and getStaticPaths, I was able to dynamically generate pages for each blog post and display them individually. However, I encoun ...

Issue with justify-content in Bootstrap 5 still unresolved

Currently working with Bootstrap 5 and have set up 4 cards. My goal is to position the second card on the left side. I've applied the class justify-content-xl-start to the card, however, it doesn't seem to be functioning as expected. I also attem ...

Creating Three-Dimensional Faces in THREE.BufferGeometry

I have programmatically created a basic mesh structure: var CreateSimpleMesh = new function () { var xy = [], maxX = 7, maxY = 10, river = [[0, 5], [0, 4], [1, 3], [2, 2], [3, 2], [4, 1], [5, 1], [6, 0]], grassGeometry ...