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

Tips for utilizing the "get" method in React to submit a form

Is there a way to submit a form using the "get" method to an external URL in react? Similar to how it is done in HTML like in this example: https://www.example.com/form But instead, to a third party URL...? Can I achieve something like this? The goal is ...

Handling mousewheel events for child elements and their parent element

I developed a custom jQuery plugin that replaces the default scrollbar with my own, managing mousewheel and bar dragging events. The issue arises when I place content containing my custom scrollbar within another content also using my scrollbar. When I sc ...

Encountering an "undefined" error while implementing a registration system in Node.js and attempting to retrieve

Having recently delved into the world of javascript and nodejs, I am currently working on developing a registration system. The issue I'm facing is related to an error message indicating that "isEmail" is undefined. I have included my form validator a ...

How can one generate an HTML element using a DOM "element"?

When extracting an element from an HTML page, one can utilize a DOM method like .getElementById(). This method provides a JavaScript object containing a comprehensive list of the element's properties. An example of this can be seen on a MDN documentat ...

Receive header information from jQuery AJAX POST request for Set-Cookie

Currently utilizing YouTrack as our tracking system. YouTrack includes a rest webservice that allows you to fetch information from the system. However, I am encountering difficulties with authorization as I keep receiving a forbidden error. Upon sending a ...

adjusting the dimensions of images to ensure uniformity in size

After many attempts, I am still struggling to resize my image. Can anyone offer assistance? I want all images to have the same dimensions. Here is the HTML code: <link href='https://fonts.googleapis.com/css?family=Indie+Flower' rel='sty ...

Leveraging JavaScript Functions in HTML

I am having an issue with a JavaScript file containing two similar functions that are executed through an HTML form. While the first function runs smoothly, the second function does not display correctly. It seems like I might be calling or executing the ...

Alert: Github Dependabot has flagged Babel as vulnerable to arbitrary code execution when compiling meticulously designed malicious code

My Github Repository's Security section is flagging this issue as Critical for both my Frontend and Backend code. I'm having trouble grasping the nature of this alert. Can someone explain what flaw it represents? After updating my dependencies, ...

What is the importance of having the same data type for the searchElement in the argument for Array.prototype.includes()?

Is there an issue with my settings or is this a feature of TypeScript? Consider the code snippet below: type AllowedChars = 'x' | 'y' | 'z'; const exampleArr: AllowedChars[] = ['x', 'y', 'z']; f ...

Does the react key have scope limited to the local environment or does it have

After reading this intriguing article discussing the use of the index as a react key, I began to ponder. Imagine having two distinct lists: <List1> <el key="1" /> <el key="2" /> </List1> <List2> <other-el key="1" / ...

What is the best way to interact with an element in Python Selenium once it has been located?

I have been working on a script that is supposed to retrieve the attribute of an element and then click on it if the value is true. However, I keep encountering an error in my code. This is the snippet of code I am using: from selenium import webdriver d ...

The z-index is not functioning properly in terms of layering correctly

Seeking advice on z-index... I'm experimenting with the code and trying to get my id="hidebar" to appear above the "content" and "content-inner" divs. Apologies if this is elementary, but I'm having some trouble =D CSS structure file: body { ...

What is the best way to position a div to float or hover from the bottom after it has been

I am working on creating a menu where clicking it will reveal a submenu at the bottom, but I'm encountering an issue. Currently, in my code, the submenu is appearing from right to left before moving down. Here is my code: <meta name="viewport" co ...

Could use some assistance in developing a custom jQuery code

Assistance Needed with jQuery Script Creation <div>Base List</div> <div id="baseSection"> <ul class="selectable"> <li id="a">1</li> <li id="b">2</li> <li id="c">3</li> ...

Implementing login functionality in an Angular application with the help of Kinvey.Social and utilizing the Promise API

I have been utilizing the Kinvey HTML5 library in an attempt to create a client-side application that integrates Google identities for Login. While the Oauth transaction appears to be functioning properly, I am encountering an issue with toggling the visib ...

Align the text to the right within a display flex container

Below is the code snippet: <div className="listContent"> <div> <div className="titleAndCounterBox"> <div className="headerListTitle">{list.name}</div><br /> <div ...

Get back a variety of substitutions

I have a variety of different text strings that I need to swap out on the client side. For example, let's say I need to replace "Red Apple" with "Orange Orange" and "Sad Cat" with "Happy Dog". I've been working on enhancing this particular ques ...

What is the best way to obtain a list of all the modules that are currently accessible in AngularJS

When declaring an Angular module, I specify its dependencies as follows: const myModule = angular.module("MyModuleName", ["Dep1", "Dep2", "Dep3"]); Each dependency comes with its own set of dependencies, directives, controllers, etc. Is there a way to qu ...

What is the best way to define file paths in a webpage to ensure that the same file works seamlessly on both server and

Currently, I am working on developing a website locally with the intention of later transferring it via FTP to my server. In my index.php file, there is a line that reads: <?php include($_SERVER['DOCUMENT_ROOT'] . "/includes/header.php");?&g ...

The property 'caseSensitive' is undefined and cannot be read

After creating a simple code, I am puzzled by an error message that seems to be case sensitive. However, the code appears correct based on my understanding. Here is the code snippet: App.js const express = require('express'); const path = requir ...