Tips for displaying the content of a personalized navigation tab using jQuery

I successfully created custom tabs using JQuery. Here is the code for my custom tabs:

<div class="row">
    <div class="col-4 master-advanced-left-tab master-advanced-left-tab-active">
        <p>Item 1</p>
    </div>
    <div class="col-4 master-advanced-left-tab">
        <p>Item 2</p>
    </div>
    <div class="col-4 master-advanced-left-tab">
        <p>Item 3</p>
    </div>
</div>

<div class="item1">
    Show content from item 1
</div>
<div class="item2">
    Show content from item 2
</div>
<div class="item3">
    Show content from item 3
</div>

These are the custom styles I applied to the tabs:

.master-advanced-left-tab {
    overflow: hidden;
    cursor: pointer;
    padding-bottom: 10px;
    padding-top: 10px;
}

.master-advanced-left-tab > p {
    text-overflow: ellipsis;
    height: 20px;
}

.master-advanced-left-tab-active {
    color: #1C72DF;
    border-bottom: 3px #1C72DF solid;
}

Below you can find the function I used to activate the tabs (it's working as intended):

$('.master-advanced-left-tab').removeClass('master-advanced-left-tab-active');
elem.addClass('master-advanced-left-tab-active');
switch (elem.data('id')) {
    case 'item1':
        //show div for item1
        break;
    case 'item2':
        //show div for item2
        break;
    default:
}

While switching between tabs, I want to display the corresponding content. I attempted to use the toggle() function from JQuery and also referred to a similar post on Stack Overflow:

Bootstrap tab activation with JQuery

However, the solutions provided did not work for my non-bootstrap nav tabs. How can I effectively show the content of each tab?

Answer №1

One way to display content is by using the show() function. Another efficient method to streamline your code and make it more adaptable is to convert clickable div elements to a tags and utilize the href attribute to specify which content should be shown. This approach eliminates the need for multiple if statements or switch cases, as it can handle an unlimited number of tabs. Additionally, this technique allows you to automatically open tabs when the page loads based on the URL fragment. Give it a try:

let $tabs = $('.tab-content');
let $triggers = $('.master-advanced-left-tab').on('click', function(e) {
  e.preventDefault();
  $triggers.removeClass('master-advanced-left-tab-active'); 
  var $elem = $(this).addClass('master-advanced-left-tab-active');
  
  $tabs.hide();
  $tabs.filter($elem.attr('href')).show();  
});

$triggers.first().trigger('click');
.master-advanced-left-tab {
  display: block;
  overflow: hidden;
  cursor: pointer;
  padding-bottom: 10px;
  padding-top: 10px;
}

.master-advanced-left-tab>p {
  text-overflow: ellipsis;
  height: 20px;
}

.master-advanced-left-tab-active {
  color: #1C72DF;
  border-bottom: 3px #1C72DF solid;
}

.tab-content {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <a href="#item1" class="col-4 master-advanced-left-tab">
    <p>Item 1</p>
  </a>
  <a href="#item2" class="col-4 master-advanced-left-tab">
    <p>Item 2</p>
  </a>
  <a href="#item3" class="col-4 master-advanced-left-tab">
    <p>Item 3</p>
  </a>
</div>
<div class="tab-content" id="item1">
  Show content from item 1
</div>
<div class="tab-content" id="item2">
  Show content from item 2
</div>
<div class="tab-content" id="item3">
  Show content from item 3
</div>

Answer №2

hide and show can be utilized as methods for achieving this goal. Hopefully, this information proves helpful.

$('.master-advanced-left-tab').click(function(e){
 
    $(this).addClass('master-advanced-left-tab-active').siblings().removeClass('master-advanced-left-tab-active')

   var class1 = $(this).attr('data-id')
    $('.'+class1+'').removeClass('hide').siblings().addClass('hide')

})
.master-advanced-left-tab {
            overflow: hidden;
            cursor: pointer;
            padding-bottom: 10px;
            padding-top: 10px;
        }

            .master-advanced-left-tab > p {
                text-overflow: ellipsis;
                height: 20px;
            }

        .master-advanced-left-tab-active {
            color: #1C72DF;
            border-bottom: 3px #1C72DF solid;
        }
        .hide
        {
        display:none;
        }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<div class="row">
    <div class="col-4 master-advanced-left-tab master-advanced-left-tab-active" data-id="item1">
        <p>Item 1</p>
    </div>
    <div class="col-4 master-advanced-left-tab" data-id="item2">
        <p>Item 2</p>
    </div>
    <div class="col-4 master-advanced-left-tab" data-id="item3">
        <p>Item 3</p>
    </div>
</div>
<div class="wrap">
<div class="item1  ">
    Show content from item 1
</div>
<div class="item2 hide">
    Show content from item 2
</div>
<div class="item3 hide">
    Show content from item 3
</div>
</div>

Answer №3

Take a look at the code snippet below:

<div class="row">
  <div class="col-4 master-advanced-left-tab master-advanced-left-tab-active" data-id="item1">
    <p>Item 1</p>
  </div>
  <div class="col-4 master-advanced-left-tab" data-id="item2">
    <p>Item 2</p>
  </div>
  <div class="col-4 master-advanced-left-tab" data-id="item3">
    <p>Item 3</p>
  </div>
</div>

<div class="content-item item1 active">
    Show content from item 1
</div>
<div class="content-item item2">
    Show content from item 2
</div>
<div class="content-item item3">
    Show content from item 3
</div>

To customize the CSS, you can add the following lines:

.content-item  {  
   display: none
}
.content-item.active  {
   display: block
}

Subsequently, in JavaScript:

$('.master-advanced-left-tab').click(function (){
  let elem = $(this);
  $('.master-advanced-left-tab').removeClass('master-advanced-left-tab-active');
  $('.content-item').removeClass('active');
  elem.addClass('master-advanced-left-tab-active');
  switch (elem.data('id')) {
      case 'item1':
        $('.item1').addClass('active')
        break;
      case 'item2':
        $('.item2').addClass('active')
        break;
      default:
        $('.item3').addClass('active')
  }
}) 

This demo illustrates the functionality: https://codepen.io/phuongnm153/pen/vYBXBGM

Answer №4

Try using a more responsive approach instead of 'swith', like the example below:

function switchTab(element) {
  // remove 'active' class from item and tab to prevent multiple
  // tab selection
  $('.master-advanced-left-tab').removeClass('active');
  $('.tab').removeClass('active');
  
  // add class 'active' to clicked item and proper tab
  // tab class is taken from 'data-tab' property from item in html
  $(element).addClass('active');
  $('.tab.' + $(element).data('tab')).addClass('active');
}

// switch tab to first one at initialization to ensure a default tab is selected
// You can also achieve this by adding class 'active' to
// 'master-advanced-left-tab' and 'tab' item in the HTML
switchTab( $('.master-advanced-left-tab:first-child') );

// event handler for switching tabs on click
$('.master-advanced-left-tab').on('click', function(){
  switchTab(this);
})
.master-advanced-left-tab {
  overflow: hidden;
  cursor: pointer;
  padding-bottom: 10px;
  padding-top: 10px;
}

.master-advanced-left-tab > p {
  text-overflow: ellipsis;
  height: 20px;
}

/* changed from .master-advanced-left-tab-active for brevity */
.master-advanced-left-tab.active {
  color: #1C72DF;
  border-bottom: 3px #1C72DF solid;
}

.tab {
  height: 0;
  overflow:hidden;
}

.tab.active {
  height: auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="row">
  <!--  utilize 'data-tab' attribute for selecting the correct tab with JS function -->
  <div data-tab="item1" class="col-4 master-advanced-left-tab">
    <p>Item 1</p>
  </div>
  <div data-tab="item2" class="col-4 master-advanced-left-tab">
    <p>Item 2</p>
  </div>
  <div data-tab="item3" class="col-4 master-advanced-left-tab">
    <p>Item 3</p>
  </div>
</diV>

<div class="tab item1">
  Show content related to item 1
</div>
<div class="tab item2">
  Display content corresponding to item 2
</div>
<div class="tab item3">
  Present content associated with item 3
</div>

Answer №5

Take a look at my custom tab view

 
$('.nav.nav-tabs li').click(function() { 
        $('.nav.nav-tabs li').removeClass('active');
        $(this).addClass('active');
        $(this).parent('.nav.nav-tabs').next('.tab-content').find('.tab-pane').removeClass('active');
        $($(this).find('a').attr('data-href')).addClass('active');
    });
 
.nav.nav-tabs{
    display: inline;
}
.nav-tabs > li {
  float: left;
  list-style: none;
}

.nav-tabs > li > a {
  margin-right: 1rem;
  padding-top: .25rem;
  padding-bottom: .25rem;
  line-height: 1.5rem;
  border-bottom: 2px solid transparent;
  color: rgba(0, 0, 0, .87);
  display: inline-block;
  text-decoration: none;
  cursor:pointer;
}

.nav-tabs > .active > a, .nav-tabs > .active > a:focus, .nav-tabs > .active > a:hover {
  color: rgba(0, 0, 0, .87);
  border-bottom-color: rgba(0, 0, 0, .87);
  cursor: default;
}

.tab-content {
  width:100%;
  display:block;
  
}
.tab-content .tab-pane {
  display: none;
  padding: 1rem 0;
}
.tab-content > .tab-pane.active {
  display: block;
}
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<ul class="nav nav-tabs list-unstyled xs-my3">
                                <li class="active"><a data-href="#location-stats" data-toggle="tab">Stats</a></li>
                                <li class=""><a data-href="#location-nearby" data-toggle="tab">Nearby</a></li>
                                <li class=""><a data-href="#location-travel" data-toggle="tab">Commute</a></li>
                                <li class=""><a data-href="#location-schools" data-toggle="tab" class="xs-mr0">Schools</a>                </li>
                            </ul>
                            <div class="tab-content">
                                <div class="tab-pane xs-relative active" id="location-stats">
                <p>Stats</p>
                                </div>
                <div class="tab-pane xs-relative " id="location-nearby">
                <p>Nearby</p>
                                </div>
                <div class="tab-pane xs-relative " id="location-travel">
                <p>Commute</p>
                                </div>
                <div class="tab-pane xs-relative " id="location-schools">
                <p>Schools</p>
                                </div>
               </div>
               
  </body>
  </html>

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

"Combine JSON data using an observable based on the ID field

Consider two distinct REST services in my project: todo.service.ts user.service.ts Below are the properties defining each object: todo: userId, title, id, completed user: id, name, email, etc Both services return an Observable with collections conformi ...

Invoke the do_action function with JavaScript/jQuery

After successfully logging in through Facebook, my AJAX function sends information to the userpro_ajax_url. In order to run a do_action function within the success block, I am trying the following: <?php ob_start(); do_action('userpro_social_l ...

Scheduled tasks on Google Cloud Platform's App Engine are failing to run over the weekend

I am facing an issue with running a cron job in my node/express application using the node-cron library. The application is hosted on Google Cloud App Engine. My aim is to automate sending emails every day at 9 AM, but the cron seems to only work from Mon ...

Best practices for distinguishing between template and style for mobile and desktop in Angular 2 components

Creating templates for mobile and desktop requires unique designs, but both share common components. To ensure optimal display on various devices, I plan to store separate templates and designs for mobile and desktop in distinct files. The goal is to inc ...

How to utilize a Boolean return value in React Class component following a promise fetch operation

Hello, I have a question about a class I am working on in React. When I call Auth.isAuthenticated() from another component, it always returns false, even though the server is returning a 200 response which should set this.authenticated to true. How can I ...

What steps should I follow to enable a tooltip in this specific situation using qtip?

In my database, I have tables for venues, venue types, and map icons with the following relationships: A venue belongs to a venue type A venue type belongs to a map icon Each venue result is shown on the index page as a partial. Each partial ...

How to deactivate the mobile hardware back button functionality in Ionic 2

Our team has been developing a business application and we've encountered a perplexing issue. Every time we press the mobile hardware back button, our application's GUI becomes disrupted. Despite dedicating numerous hours to finding a solution, t ...

Reactive form allows you to easily format dates

Currently, the date displayed is 1/4/2022. We need it to display in the format 01/04/2022. Can we achieve this formatting using reactive forms with the sample Model form provided below? Thank you. How can we format it when starting from transactionStartD ...

Ways to reset the selected option when the user chooses a different option using either Jquery or Vanilla JavaScript

I am currently working on a functionality to clear the select option when a different brand is selected. The issue I am facing is that when I choose another brand, the models from the previous selection are not cleared out. For example, if I select BMW, I ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

What is causing the issue with this pseudo class selector not functioning properly?

I've been experimenting with the :after selector to create an inside-border effect in every div I hover over. However, I'm facing an issue where the ":after" pseudo-class doesn't seem to work. Any insights on why this selector isn't fun ...

Receive instant access to the next dropdown option below the current selection

Check out my HTML Example <table> <tr> <select class="dropdown"> <option value="">Select answer</option> <option value="1" selected="selected">A</option> <option value="2">B</option> ...

Image selection plugin in Cordova not functioning properly

Currently, I am attempting to select multiple images from the gallery using the cordova-imagePicker plugin. It's worth noting that my project uses Cordova rather than the Ionic framework. Below is the code snippet I have implemented: <script type ...

Adding multiple text as label and sublabel in a React MUI Tooltip can be achieved by utilizing the appropriate

I'm struggling to incorporate a MaterialUI Tooltip into my React application with two separate text lines. The first line should serve as the main title, while the second line functions as a sublabel. In this screenshot provided, you can see where I ...

I am puzzled as to why the JSON response is visible in the browser but cannot be forwarded to the Ajax callback function, causing the page to remain on the initial request page

Currently, I am in the process of developing a web application that utilizes AJAX and servlet. My main focus right now is creating a functional login page for the application. Although the servlet successfully generates a response in JSON format, the issu ...

Failure to execute Ajax request when searching for a query

My personal GitHub profile viewer React application allows you to search for a profile by username. By default, my own GitHub username is provided on the landing page. However, when trying to search for another user, my ajax call is not functioning properl ...

Make a copy of an array and modify the original in a different way

Apologies for my poor English, I will do my best to be clear. :) I am working with a 3-dimensional array which is basically an array of 2-dimensional arrays. My task is to take one of these 2-dimensional arrays and rotate it 90° counterclockwise. Here is ...

Bootstrap columns are still disrupted by large images even when they have reached their maximum width and height

I have been using bootstrap templates that allow users to create displays with images and text. I previously added max-width:100% and height:auto to the img CSS, thinking it would resolve issues with large images breaking the container. However, when inse ...

Struggles with Aligning CSS Layout

I'm encountering some challenges with the layout of my webpage, particularly with alignment. Here are the issues I'm facing: The login section doesn't fit well in the header and lacks proper alignment. I aim to replicate the design from ...

Sorting a select element using Javascript/JQuery while taking into consideration the label attribute present in the options

It came to my attention that the jQuery options and examples only covered the text and value attributes, causing errors when attempting to add the label attribute. I am looking for a way to include the label attribute in the sorting process, especially whe ...