JavaScript Tab Fade Effect

I have a tab system that utilizes JavaScript to switch tabs. I am trying to implement a fade in and out effect when switching tabs. The current JavaScript simply adds or removes the clicked tab selected by the user. I have managed to partially achieve the fade in effect with JS, but it is not removing the tabs as desired.

$(document).ready(function() {
  $('ul.tabs li').click(function() {
    var tab_id = $(this).attr('data-tab');
    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current');
    $(this).addClass('current');
    $("#" + tab_id).addClass('current');
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<div class="container">
  <div class="col-md-6">
    <ul class="tabs">
      <li class="tab-link current" data-tab="tab-1">Tab One</li>
      <li class="tab-link" data-tab="tab-2">Tab Two</li>
      <li class="tab-link" data-tab="tab-3">Tab Three</li>
      <li class="tab-link" data-tab="tab-4">Tab Four</li>
    </ul>
  </div>
  <div class="col-md-6">
    <div id="tab-1" class="tab-content current">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </div>
    <div id="tab-2" class="tab-content">
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <div id="tab-3" class="tab-content">
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    </div>
    <div id="tab-4" class="tab-content">
      Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </div>
  </div>
</div>
<!-- container -->

Answer №1

To achieve a tab fadeIn effect using jQuery, you can make the following changes in your script:

1st Update:

$('.tab-content').removeClass('current');

should be updated to:

$('.tab-content').removeClass('current').hide();

2nd Update:

$("#" + tab_id).addClass('current');

should be updated to:

$("#" + tab_id).addClass('current').fadeIn();

For further assistance with fading effects in jQuery, check out Fading jQuery documentation

$(document).ready(function() {
  $('ul.tabs li').click(function() {
    var tab_id = $(this).attr('data-tab');
    $('ul.tabs li').removeClass('current');
    $('.tab-content').removeClass('current').hide();
    $(this).addClass('current');
    $("#" + tab_id).addClass('current').fadeIn();
  });
});
body {
  font: 13px Verdana;
}

.tab-content {
  display: none;
}

.tab-content.current {
  display: block;
}

.tabs {
  padding: 0;
  list-style: none;
}

.tabs li {
  display: inline-block;
  margin: 0 10px;
  padding: 6px;
  cursor: pointer;
}

.tabs li.current {
  background: red;
  color: #fff;
  cursor: initial;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
  <div class="col-sm-6">
    <ul class="tabs">
      <li class="tab-link current" data-tab="tab-1">Tab One</li>
      <li class="tab-link" data-tab="tab-2">Tab Two</li>
      <li class="tab-link" data-tab="tab-3">Tab Three</li>
      <li class="tab-link" data-tab="tab-4">Tab Four</li>
    </ul>
  </div>
  <div class="col-md-6">
    <div id="tab-1" class="tab-content current">
      Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </div>
    <div id="tab-2" class="tab-content">
      Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
    </div>
    <div id="tab-3" class="tab-content">
      Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.
    </div>
    <div id="tab-4" class="tab-content">
      Sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
    </div>
  </div>
</div>

Answer №2

$(document).ready(function(){
    var activeTab;
    $('ul.tabs li').click(function(){
        var tabID = $(this).attr('data-tab');
        $('ul.tabs li').removeClass('current');
        $('.tab-content').removeClass('current');
        if(activeTab) $("#"+activeTab).hide();
        $("#"+tabID).fadeIn("slow");
        activeTab = tabID;
        $(this).addClass('current');
    })
})

Implemented a variable to store the tab ID of the selected tab.

Answer №3

You're almost there!

A straightforward solution is to utilize fadeIn and fadeOut with jQuery, since you're already using it.

Try the following code snippet:

$(document).ready(function(){
    var last_id;
    $('ul.tabs li').click(function(){
    var tab_id = $(this).attr('data-tab');
        $('ul.tabs li').removeClass('current');
        $('.tab-content').removeClass('current');

        // Fade out elements with tab-content class
        $('.tab-content').fadeOut("slow");

        $(this).addClass('current');
        $("#"+tab_id).addClass('current');

        // fade out the last content
        if(last_id) $("#"+last_id).fadeOut();
        // Fade in the element you want to show
        $("#"+tab_id).fadeIn("slow");
        last_id = tab_id;
    })
})

For more information on both fadeIn and fadeOut, visit http://api.jquery.com/fadeout/ http://api.jquery.com/fadein/

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

Testing the scope of an Angular directive

Encountering an issue with the unit test In my code, I have: describe('test controller', function () { var =$compile, scope, rootScope; beforeEach(module('myApp')); beforeEach(inject(function (_$compile_, _$rootScope_) { ...

Jquery solution for toggling multiple Divs individually

I'm currently working on a small application that has both a sidebar menu and a header menu. My goal is to have all items in these menus toggle the visibility of content in one main window or page. When a button is clicked, I want it to show the corre ...

The JSON node fails to return a value after inserting data through an ajax request

I'm encountering an issue with a jQuery plugin that loads JSON data through an AJAX call and inserts it into an existing object. When I attempt to reference the newly inserted nodes, they show up as 'undefined', despite the data appearing co ...

The setting "break-word" within word warp attribute isn't effective for formatting my text

Here is the CSS code that I am using: .SubjectCell{ width: 300px; padding-left: 3em; padding-right: 2em; color: black; font-size: 20px; word-wrap:break-word; } I have applied this class to a table cell within a table in my datalist: <td class ...

Executing a message in Azure Service Bus using Javascript/Node.js

I am utilizing the @azure/service-bus library in a Node.js application to receive messages. The code I am using is as follows: const { ServiceBusClient } = require("@azure/service-bus"); const sbClient = new ServiceBusClient(connectionString); ...

Revolutionary web element

My vendor provides a convenient widget creation service that allows me to access their platform, input initial search form values, save them, and then easily embed the generated script code on my website to display a product search result widget. I am int ...

What strategies can be employed to minimize redundant re-rendering of React components while utilizing the useEffect hook?

Hey everyone, I'm facing a challenge in my React/Electron project where I need to minimize renders while using the useEffect hook to meet my client's requirements. Currently, I have a container/component structure with an index.js file that house ...

Align the bottom of an image with the top of text to achieve perfect vertical alignment

My goal is to arrange numerous images in a row, with text displayed below each image. Each block of text may consist of multiple lines and should be centered. While the heights of the images may vary, their widths will remain consistent. It is important th ...

What is the best way to dynamically resize a text field based on the length of the typed text

I am looking to dynamically expand the width of an input text field when a user enters text into it. I am not sure how to achieve this functionality. Any guidance or help would be greatly appreciated. Is it possible to do this using Jquery or javascript? ...

Creating a tree structure in JavaScript by parsing a collection of URLs

Hello everyone, I am currently working on creating a dynamic menu list that allows users to create elements without any depth limitations. THE ISSUE The structure of my URLs is as follows: var json_data = [ { "title" : "Food", "path" ...

Share a Node.js Express.js npm package for universal access within the project

Here is my current folder structure. /app.js /src /routes /controllers Within the routes folder, there are multiple javascript files that all require the passport.js package like so: const passport = require('passport'); Is it possible to c ...

Error is thrown when attempting to access nested elements using GetElementsByClassName within the window.onload function

I have a funky looking table on my webpage, here's an example: <body> <table class="table table-bordered"> <thead> <tr> <th>#</th> <th>Product name</th> <th>Product ...

Exploring a different approach to utilizing Ant Design Table Columns and ColumnGroups

As per the demo on how Ant Design groups columns, tables from Ant Design are typically set up using the following structure, assuming that you have correctly predefined your columns and data: <Table columns={columns} dataSource={data} // .. ...

Exploring Angular 1.5: A guide to binding a transcluded template to a component's scope

Currently, I am utilizing a form component that includes common validation and saving functions. Inputs are injected into the form as transcluded templates in the following manner: <form-editor entity="vm.entity"> <input ng-model="vm.dirt ...

Is there an equivalent of getElementById for placeholder text?

I need help automating the input of information on a webpage using JavaScript. Each field has a unique ID, like this: <div id="cc-container" class="field has-float-label"> <input placeholder="ccnumber" id="credit_card_number" maxlength="16" ...

jquery executes a function on each element that is discovered using the .find method

I am working with the following HTML code that is parsed by the system. I want to know how to perform an action on each "find" element and execute a specific function for every anchor found. HTML Code <ul> <li class="category"> <h2&g ...

Create a container-fluid design in Bootstrap with various colors

I am aiming to create a design with a fluid container featuring different background colors on each side, separated by two columns within the container. I have visualized it in this image - do you think it is feasible? https://i.stack.imgur.com/KRc2Q.pn ...

Using React and Ant Design: Sharing state between multiple <Select> components within a <Form> element

Just getting started with ReactJS and AntDesign. Currently, I am working on connecting a series of <Select> components to share state. The goal is for the selection made in the first dropdown to dynamically update the options available in the follow ...

Determine whether or not a selector has been designated

As I embark on developing my inaugural jQuery plugin, I aim to add a unique twist to its functionality. Let me clarify the main objective: The concept is basic - when an <input> field contains a title attribute, the input box will be pre-filled with ...

The replace method cannot be utilized within a function

jQuery ( function ( $ ) { var textarea = $('.project'); var $counter = $('.chars'); var limit = 200; var initial = 0; $(textarea).on('keypress keyup copy paste', function(){ displayLength(); }); function displayLen ...