Dynamically hiding elements within tabs using jQuery

Previously, I created a functionality for handling a single set of tabs. However, as the application has expanded, this functionality is no longer sufficient to accommodate multiple sets of tabs.

The initial function looked like this:

var iconTabs = function () {

    $('#icons-tabs a:not(:first)').addClass('inactive');
    $('.icons-container').hide();
    $('.icons-container:first').show();

    $('#icons-tabs a').click(function(){
        var t = $(this).attr('id');
        if($(this).hasClass('inactive')) {
            $('#icons-tabs a').addClass('inactive');
            $(this).removeClass('inactive');
            $('.icons-container').hide();
            $('#'+ t + 'C').fadeIn('slow');
        }
    });
};

And here is the corresponding html:

<div id="fragment-1" class="fragments text-center">
    <div class="icons-container" id="tab1C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="tab2C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab1"></a>
                <a href="#" class="item" id="tab2"></a>
                <a href="#" class="item" id="tab3"></a>
                <a href="#" class="item" id="tab4"></a>
            </div>
        </div>
    </div>
</div>

Now, with additional sections being added in the html, such as the second section, the code has evolved:

<div id="fragment-1" class="fragments text-center">
    <div class="icons-container" id="tab1C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="tab2C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab1"></a>
                <a href="#" class="item" id="tab2"></a>
            </div>
        </div>
    </div>
</div>

<div id="fragment-2" class="fragments text-center">
    <div class="icons-container" id="tab5C">
        {{!-- Content --}}
    </div>

    <div class="icons-container" id="ta62C">
        {{!-- Content --}}
    </div>

    <div class="fragments-parent">
        <div class="fragments-icons fragments-parent--child">
            <div class="items" id="icons-tabs">
                <a href="#" class="item" id="tab5"></a>
                <a href="#" class="item" id="tab6"></a>
            </div>
        </div>
    </div>
</div>

A JSFiddle has been provided for testing purposes:

http://jsfiddle.net/ju3a9zx5/

The goal now is to make the functionality dynamic and ensure that each set of tabs behaves independently. In the current setup, the second set of tabs does not work as intended, and the aim is to isolate the behavior of each set of tabs without interference from others.

Answer №1

It is recommended to utilize classes instead of ids when targeting tabs. In the example provided below, there are a few key changes:

  1. Replace id="tabs" and id="tabs2" with class="tabs"
  2. Adjust event handlers to target the class rather than the ids
  3. For finding related a tags, use siblings()
  4. In locating the related .container, apply .nextUntil() to find the container further down in the DOM
  5. To display initial container classes, utilize $('.tabs').next('.container')

$(document).ready(function() {

  $('.tabs a:not(:first)').addClass('inactive');
  $('.container').hide();
  $('.tabs').next('.container').show();

  $('.tabs a').click(function() {
    var t = $(this).attr('id');
    if ($(this).hasClass('inactive')) { //beginning of condition 
      $(this).siblings('a').addClass('inactive');
      $(this).removeClass('inactive');

      $(this).parent().nextUntil(':not(.container)').hide();
      $('#' + t + 'C').fadeIn('slow');
    }
  });

});
.tabs {
  width: 100%;
  height: 30px;
  border-bottom: solid 1px #CCC;
  padding-right: 2px;
  margin-top: 30px;
}

a {
  cursor: pointer;
}

.tabs a {
  float: left;
  list-style: none;
  border-top: 1px solid #ccc;
  border-left: 1px solid #ccc;
  border-right: 1px solid #ccc;
  margin-right: 5px;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  outline: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: small;
  font-weight: bold;
  color: #5685bc;
  ;
  padding-top: 5px;
  padding-left: 7px;
  padding-right: 7px;
  padding-bottom: 8px;
  display: block;
  background: #FFF;
  border-top-left-radius: 3px;
  border-top-right-radius: 3px;
  text-decoration: none;
  outline: none;
}

.tabs a.inactive {
  padding-top: 5px;
  padding-bottom: 8px;
  padding-left: 8px;
  padding-right: 8px;
  color: #666666;
  background: #EEE;
  outline: none;
  border-bottom: solid 1px #CCC;
}

.tabs a:hover,
.tabs a.inactive:hover {
  color: #5685bc;
  outline: none;
}

.container {
  clear: both;
  width: 100%;
  border-left: solid 1px #CCC;
  border-right: solid 1px #CCC;
  border-bottom: solid 1px #CCC;
  text-align: left;
  padding-top: 20px;
}

.container h2 {
  margin-left: 15px;
  margin-right: 15px;
  margin-bottom: 10px;
  color: #5685bc;
}

.container p {
  margin-left: 15px;
  margin-right: 15px;
  margin-top: 10px;
  margin-bottom: 10px;
  line-height: 1.3;
  font-size: small;
}

.container ul {
  margin-left: 25px;
  font-size: small;
  line-height: 1.4;
  list-style-type: disc;
}

.container li {
  padding-bottom: 5px;
  margin-left: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="tabs">

  <a id="tab1">test1</a>
  <a id="tab2">test2</a>
  <a id="tab3">test3</a>
  <a id="tab4">test4</a>

</div>
<div class="container" id="tab1C">1Some content</div>
<div class="container" id="tab2C">2Some content</div>
<div class="container" id="tab3C">3Some content</div>
<div class="container" id="tab4C">4Some content</div>

<div class="tabs">

  <a id="tab5">test1</a>
  <a id="tab6">test2</a>
  <a id="tab7">test3</a>
  <a id="tab8">test4</a>

</div>
<div class="container" id="tab5C">5Some content</div>
<div class="container" id="tab6C">6Some content</div>
<div class="container" id="tab7C">7Some content</div>
<div class="container" id="tab8C">8Some content</div>

Answer №2

After experimenting with your fiddle, one suggestion stands out: replace id="tabs" with class="tabs", and update the selectors in both your javascript and css files. This adjustment should help you get started smoothly.

As a developer, I would recommend creating a jQuery plugin and implementing the code within an each() function to enhance flexibility, scalability, and maintainability.

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

What is the method for locating all anchor tags "In General" within the inner HTML of a div using XPath?

This query is related to a discussion on anchor tags in this thread. I am interested in identifying all anchor tags within a string. The scenario provided below is similar to the aforementioned issue, however, I aim to accomplish this using xpath and angu ...

Using an Ajax Post Call to send FormData leads to a Get request instead

Having trouble with sending a simple form via POST method. I load the form content using AJAX: $(function() { var arg = { "operation": "upload", "step": "0" ...

Utilizing i18n's useTranslation and Redux's connect Higher Order Components to export components efficiently

My application has been utilizing Redux for quite some time, with the component exports structured like this: export default connect(mapStateToProps, mapDispatchToProps)(MyComponent); Now, I am integrating an i18n translation library and would like to use ...

A step-by-step guide on setting up a confirmation pop-up message using Gravity Forms

Has anyone attempted to implement a pop-up confirmation message in Gravity Forms? I am also looking to prevent the form from disappearing after submission. By the way, I have selected text as the confirmation type in my Gravity Form settings because I do ...

I am having trouble getting Vue.js to function properly within HTML when using Django. Can someone please lend me a

The code run Here is the HTML document: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Register</title> <!--javascript extensions--> <script src=' ...

Should using module.export = [] be avoided?

Having two modules that both need access to a shared array can be tricky. One way to handle this is by creating a separate module just for the shared array, like so: sharedArray.js module.exports = []; In your module files, you can then use it like this ...

Rendering a ImageBitMap/Image on an OffScreenCanvas using a web-worker

In my vue.js application, I have implemented vue-workers/web-workers to handle image processing tasks such as scaling and cropping in the background after a user uploads images. Due to the lack of support for Canvas and Image Object in web workers, I opte ...

"Automate the process of manual content duplication with JavaScript's for each replacement

Seeking a solution to automate the selection process without writing individual JS scripts for every input. For instance, having 10 double inputs (total of 20 inputs) and utilizing the each() function or other methods by only declaring selectors. Find th ...

No data being sent from AJAX to PHP script

After serializing the form data, logging it, and sending it to the PHP file, I am facing an issue where it returns null. In my jQuery code: $('#preregister').submit(function () { if(checkemail("prereg_email")) { var data; ...

Error: Preflight request returned a 405 HTTP status code when querying Ionic + CI backend

I am currently working on my first app using ionic with a codeigniter backend. However, I am encountering the "Response for preflight has invalid HTTP status code 405" issue in ionic + CI backend. Can anyone help me solve this problem? This is my controll ...

Utilizing JSON with ASP.NET WebForms

Is it recommended to use JSON, JQuery & ASP.NET 2.0 webforms together or is it better suited for MVC with ASP.NET 3.5 & 4.0? When incorporating JSON, should I utilize gridviews and repeaters controls for binding JSON data or should I create custom tables f ...

I am facing difficulty in incorporating an IP address or URL within an IFRAME in my Cordova Android application

This page does not allow any iframes to load except for the YouTube video URL. When attempting to use any other iframe URL, the following error code is displayed: Error : net::ERR_BLOCKED_BY_RESPONSE In the example below, any URL or IP address fails to l ...

What makes ngFor unique in Angular that allows it to not require keys like in Vue and React?

I recently delved into learning Angular a few weeks back. In Vue and React, we typically use a unique key when rendering an array of elements to optimize the rendering process, especially when there are changes in the elements' order or quantity. As a ...

Issues with Ajax arise once URL re-routing is activated

When loading content using AJAX and ASP.NET web-methods, the following code is used to trigger the Ajax request: var pageIndex = 1; var pageCount; $(window).scroll(function () { if ($(window).scrollTop() == $(document).height() - $(window).height()) ...

Limiting uploaded files in HTML5

<input type="file" accept=".csv" /> This code snippet enables users to upload .txt files or any other type of file as well. What is the method to limit the types of files allowed in HTML5? ...

Assign a value to the <li> element and modify the prop when the user clicks using vue.js

I've been attempting to update props from child to parent using the $event in an @click event. I sent the data and $event from the parent to the child as shown below. in the parent component: <v-filter :sortTypePrice="sortTypePrice" :sort ...

What could be causing the React-Router-Dom Outlet to not show the component?

I am working on a component that houses four different components. const ProtectedRoute = () => { return ( <> <Header /> <div className='flex h-screen overflow-hidden'> <div className="md:block h ...

JQuery Submission with Multiple Forms

Hey everyone! I have a jQuery form with multiple fieldsets that switch between each other using jQuery. Eventually, it leads to a submit button. Can someone assist me by editing my jfiddle or providing code on how I can submit this data using JavaScript, j ...

Preloaded background images are loaded twice

I have a background image that I am preloading and caching, but my code is not reading it from the cache. It keeps loading the image as if it is not cached. Even though I have 8 images in the "imgSrcArray," I have simplified this example by hard coding jus ...

Incorporate Angular exclusively in pages that are dynamically loaded via ajax requests

<html> <head> <title></title> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script> </head> <body> <div id="ajax-content-here"> </div> </body> ...