JavaScript Bootstrap tab component

I want to utilize bootstrap's card/tab functionality to create a card with tabs. The card will have 3 tabs, each corresponding to its own active 'card body.'

Below is my existing code:

<div class="col-lg-8 col-md-12 col-sm-12">
      <div class="page-header">
        <h2>Social Media</h2>      
      </div>
      <div class="card text-center">
        <div class="card-header">
          <ul class="nav nav-tabs card-header-tabs">
            <li class="nav-item">
              <a class="nav-link active" href="#insta">Instagram</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#face">Facebook</a>
            </li>
            <li class="nav-item">
              <a class="nav-link" href="#twit">Twitter</a>
            </li>
          </ul>
        </div>
        <div class="card-body">
          <div id="insta">Instagram</div>
          <div id="face">Facebook</div>
          <div id="twit">Twitter</div>
        </div>
      </div>
    </div>

$(document).ready(function(){
$(".nav-tabs a").click(function(){
    $(this).tab('show');
});
});

The code builds the card correctly and displays the appropriate tab headers with their respective links.

My goal is to have the text display in the 'card body' only when the corresponding tab is active. Currently, all three lines of text are displaying in the main tab's body.

Although the javascript appears correct, the tabulation is not functioning as expected.

You can view the codepen here:

https://codepen.io/anon/pen/gKLJrm

Answer №1

If you want to create functional tabs, make sure to use the appropriate markup for tabs using tab-content and tab-pane. Here is a helpful resource: https://getbootstrap.com/docs/4.0/components/navs/#javascript-behavior

(no jquery is required)

Check out this example for reference:

  <div class="card text-center">
        <div class="card-header">
            <ul class="nav nav-tabs card-header-tabs">
                <li class="nav-item">
                    <a class="nav-link active" data-toggle="tab" href="#insta">Instagram</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="tab" href="#face">Facebook</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" data-toggle="tab" href="#twit">Twitter</a>
                </li>
            </ul>
        </div>
        <div class="tab-content card-body">
            <div id="insta" class="tab-pane active">Instagram</div>
            <div id="face" class="tab-pane">Facebook</div>
            <div id="twit" class="tab-pane">Twitter</div>
        </div>
  </div>

Make sure that both the nav-link and tab-pane elements have the active class set.

Answer №2

Hopefully this solution resolves your issue

$(document).ready(function() {
$('.nav-item a').on('click', function(e){
var currentAttrValue = $(this).attr('href');
// Show/Hide Tabs
$('.tab-content ' + currentAttrValue).show().siblings().hide();
// Change/remove current tab to active
$(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});
li.nav-item.active a {
    background: #fff;
    border: 1px solid #eee;
    border-bottom: none
}
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" integrity="sha384-WskhaSGFgHYWDcbwN70/dfYBj47jz9qbsMId/iRN3ewGhXQFZCSftd1LZCfmhktB" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous></script>

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js" integrity="sha384-smHYKdLADwkXOn1EmN1qk/HfnUcbVRZyYmZ4qpPea6sjB/pTJ0euyQp0Mk8ck+5T" crossorigin="anonymous"></script>

        <div class="col-lg-8 col-md-12 col-sm-12">
          <div class="page-header">
            <h2>Social Media</h2>      
          </div>
          <div class="card text-center">
            <div class="card-header">
              <ul class="nav nav-tabs card-header-tabs" id="myTabs">
                <li class="nav-item active">
                  <a class="nav-link" href="#insta">Instagram</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#face">Facebook</a>
                </li>
                <li class="nav-item">
                  <a class="nav-link" href="#twit">Twitter</a>
                </li>
              </ul>
            </div>
            <div class="card-body tab-content">
              <div id="insta" class="tab-pane active">Instagram</div>
              <div id="face" class="tab-pane">Facebook</div>
              <div id="twit" class="tab-pane">Twitter</div>
            </div>
          </div>
          <!-- END WIDGET 2 -->
        </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

How to efficiently calculate totals in an HTML table using JavaScript/jQuery

I have a gridview that displays product details and includes a quantity textbox that is not linked to any database. For each row, I want it to show the cost (price * quantity) and the total cost for all rows in a label below. However, I am encountering a f ...

What is causing my for/in loop to return null results, while the regular for loop works perfectly fine? (VISUALS included)

My goal is to iterate through an array of objects using a for/in loop in order to log specific properties of each object to the Chrome dev console. However, I am encountering issues as I keep getting null values. As a workaround, I attempted to use a regul ...

Having trouble retrieving JavaScript data sent via AJAX using the Playframework2 DynamicForm object. encountering an error: `{data[undefined]=}`

When I send a Javascript array via Ajax using the POST method like this: $.post(assignmentsubmitAddress, submittedUnitsArray, I receive a Status OK response. However, when I try to retrieve that data on the server using the Play Framework 2 Dynamic form ...

`Is there a way to choose several radio buttons with varying names using just one label?`

Is there a way to choose multiple radio buttons with different names using just one label? Here's an example of what I'm attempting to accomplish... <input id="1A" type="radio" name="first" value="A">firstA<br> <input id="1B" typ ...

What is the best way to refresh jCarousel following the loading of AJAX content?

After purchasing a custom jCarousel JavaScript (available at http://pastebin.com/BwsVpNjr), I encountered an issue when trying to load content with AJAX. The carousel breaks because it is unable to detect the width or height. Is there a way to have jCarous ...

Creating a Conditional "Retrieve Script File" Function in JavaScript Without Dependencies

At the company where I work, we have numerous clients with their own websites that are connected to our system through a linking mechanism. Essentially, these clients have a link on their website that directs users to our site upon clicking. I am working ...

How can I troubleshoot TypeScript in Ember CLI using VSCode?

After doing some research on stackoverflow, I came across this post: How to debug Javascript-Code produced and served by ember-cli? That post was created back in 2014, so I'm hoping that there have been updates or new features added since then. I&ap ...

Make sure to wait for the fetch response before proceeding with the for loop in JavaScript using Node.js

I am facing an issue with my function that connects to a SOAP web service. The problem arises from the fact that the web service has limited connections available. When I use a for or foreach loop to search through an array of items in the web service, aro ...

Creating a jQuery accordion: A step-by-step guide

I'm currently working on building a dynamic accordion using jQuery where only one element can be open at a time. When a new element is opened, the previous one should close. I've managed to make it open and hide the button when opening it, but I ...

Shutting down the jQuery pop-up

I am struggling with trying to display this code as a popup on my website. Here is the code I have: <div id="myDialog" title="myTitle"> <div class="table_cell"> <div class="message"></div> </div> <div class="tabl ...

The issue of Ajax response not triggering the ng-click function

When attempting to pass data through an AJAX return, I encountered an issue with a function that writes an ng-click in Angular 1. The code snippet is as follows: $.ajax({ 'method': 'GET', 'url': base_url +&apos ...

I'm struggling to figure out why my mr-auto isn't functioning properly (built with Bootstrap)

How can I align all my content to the right before the "home" link in this navbar? I've tried using mr-auto but it's not working. Any suggestions? <header class="header_area"> <div class="main-menu"> &l ...

Disabling images in Selenium Webdriver using Chromedriver - A step-by-step guide

The script provided above fails to prevent images from loading in Selenium's ChromeDriver. const { Builder, By, Key, until } = require('selenium-webdriver'); require('chromedriver'); (async function example() { const chro ...

Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake? When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and ...

I am having trouble displaying SASS styles in the browser after running webpack with node

In my current project for an online course, I am utilizing sass to style everything. The compilation process completes successfully without any errors, but unfortunately, the browser does not display any of the styles. The styles folder contains five file ...

Remove information inside table cells <td> when the table is in edit mode by using JavaScript or jQuery

I am facing an issue where I need to clear the data in a HTML td onfocus, especially in an editable table using JQuery tabledit. The table is populated with data from a database and I want to be able to edit a td without having to manually delete the exist ...

Angular Bootstrap-Select: Displaying options even after selection

There seems to be a bug in the angular bootstrap select demo section. After selecting an option, the dropdown continues to display options instead of hiding them. This issue does not occur when the ng-model attribute is omitted. You can view an EXAMPLE he ...

fetch and modify data simultaneously in firebase

Is there a way to retrieve a value from a Firebase document and immediately update it? I am familiar with methods for updating documents and retrieving their values separately, but how can I accomplish both in one go? update firebase.firestore().collecti ...

What sets res.redirect apart from res.sendfile?

I recently completed a tutorial challenge where I set up a 'failure' page that included a 'Try again' button. This button redirects the user back to '/signup/html'. In my code, I utilized app.post("/failure", (req, r ...

Is it best to remove trailing/leading whitespace from user input before insertion into the database or during the input process?

There's something I've been pondering that pertains to MVC platforms, but could also be relevant to any web-based platform that deals with user input forms. When is the best time and method to eliminate leading/trailing whitespace from user inpu ...