JavaScript- Tabbed Navigation with Lists as the Content

Currently, I am facing a frustrating issue in finding a suitable solution.

My website uses tabs that utilize the UL, LI system, similar to most tab systems found in tutorials.

The problem arises because the javascript on my site interferes with using the UL, LI system within my content.

This javascript adds an active class to a selected tab and removes it when switching to another tab, thereby causing all LI elements to inherit the "display:none;" property.

I am seeking advice on the best approach to resolve this dilemma.

Below is the javascript section:

$(function () {
var container = $('.tabs-container'),
    tabs      = container.find('.tabs li'),
    links     = tabs.find('a'),
    contents  = container.find('.contents li');

links.click(function (e) {
    e.preventDefault();
});

tabs.on('click', function () {
    var $this    = $(this),
        $id      = $this.find('a').attr('href'),
        $target  = container.find('.contents ' + $id);

    if ($this.hasClass('active'))
        return;

    tabs.removeClass('active');
    $this.addClass('active');

    contents.removeClass('active').hide();
    $target.fadeIn(500).addClass('active');
});
});

For reference, here is the JSFiddle link with the code (https://jsfiddle.net/f6jLt91d/)

Upon inspecting the code, you will notice that the initial tab displays a list properly only after manually adding the "display:inline" rule to the style. However, switching between tabs causes the list to disappear upon returning to the first tab.

I believe there may be a minor oversight or mistake causing this issue, but despite spending the last three days troubleshooting, I have yet to find a suitable resolution. Any suggestions?

Answer №1

It is important to provide a specific CSS selector, especially when dealing with content containing <li>. This fix is quite simple - only hide the top-level <li>s without affecting the rest of the tree structure. By using child selectors instead of descendant selectors, the issue can be resolved.

tabs      = container.find('.tabs > li'),
contents  = container.find('.contents > li');

Snippet

$(function () {
  var container = $('.tabs-container'),
      tabs      = container.find('.tabs > li'),
      links     = tabs.find('a'),
      contents  = container.find('.contents > li');

  links.click(function (e) {
    e.preventDefault();
  });

  tabs.on('click', function () {
    var $this    = $(this),
        $id      = $this.find('a').attr('href'),
        $target  = container.find('.contents ' + $id);

    if ($this.hasClass('active'))
      return;

    tabs.removeClass('active');
    $this.addClass('active');

    contents.removeClass('active').hide();
    $target.fadeIn(500).addClass('active');
  });
});
.tabs-container {
  margin-left:auto;
  margin-right:auto;
  width: 400px;
  float: none;
  list-style: none;
  position: relative;
  margin: 0px 0 0 10px;
  text-align: left;
}

/* Remaining CSS code from the original text */

<em>(Original CSS code omitted for brevity)</em>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="tabs-container">
  <ul class="tabs cf">
    <li class="active"><a href="#one">Tab 1</a></li>
    <li><a href="#two">Tab 2</a></li>
    <li><a href="#three">Tab 3</a></li>
    <li><a href="#four">Tab 4</a></li>
  </ul>

  <ul class="contents cf">
    <li id="one" class="active">
      ...
    </li>
    <li id="two">
      ...
    </li>
    <li id="three">
      ...
    </li>
    <li id="four">
      ...
    </li>
  </ul>
</div>

Fiddle: https://jsfiddle.net/engcr3qp/

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

Clean coding techniques for toggling the visibility of elements in AngularJS

Hey everyone, I'm struggling with a common issue in my Angular projects: app.controller('indexController', function ($scope) { scope.hideWinkelContainer = true; scope.hideWinkelPaneel = true; scope.headerCart = false; scope. ...

What is the best way to retrieve an object from every function?

I'm dealing with a <div> containing radio buttons: <div id='RB-01'> <span>Item_1</span><input type='radio' name='RB01' value='1'><br /> <span>Item_2</span><inp ...

Displaying a PHP variable within an HTML tag that has been previously output within a PHP block

I'm struggling with printing a variable that was already echoed in a php tag within an html tag. Specifically, I want to print the variable $A in an h1 tag. Here is my code: <?php while($pr = mysql_fetch_assoc($qAccess)) { $ ...

Take out the username field from the registration form in Woocommerce

Is there a way to eliminate the username section from the registration form on woocommerce? I attempted to remove certain lines from the woocommerce/myaccount/login-form.php <?php if ('no' === get_option( 'woocommerce_registration_gene ...

Utilize jQuery to toggle the visibility of one specific div among others with the same class

I'm currently working on a comment and like system similar to Facebook. However, I am struggling to select the specific div element! Here is a snippet of my current HTML: <div class='activoptions'><a href='#'>Like< ...

Accessing a hyperlink within the existing page

How can I make a hyperlink in an HTML document that opens the linked document (link1.html) under the link on the same page? links.html: <body> <h3>Links</h3< <a href="link1.html">link1</a> </body> Desired out ...

Hold off on refreshing the page until all the $.get calls have finished executing

I am currently using a piece of JavaScript to execute an Ajax call which returns XML data. This XML is then processed, and another Ajax call is made for each "record" found in the XML to delete that record. However, I am facing an issue where the JavaScrip ...

Implementing Angular routing within the Express framework can enhance the user experience

I'm diving into Angular and Node/Express for the first time. I've successfully set up a node/express server and loaded the main index.jade file. However, I'm struggling to use Angular for routing between links on this page. The console consi ...

Retrieve JSON data from Form Submission

While I am not a front end developer, I have been trying my hand at it recently. I hope that the community here can assist me with an issue I am facing. I have a form that is supposed to send files to a server-side API like shown below: <form id="uploa ...

Learn the process of incorporating a plugin into a React JS project

As a ReactJs beginner, I am encountering an issue while trying to import a new plugin in my react app. I am currently working on React without using node or npm as shown below. <!-- some HTML --> <script src="https://unpkg.com/babel-standalone@6 ...

Shadow border added to each div creates a unique navigation tab for easy access

#container { position: fixed; height: 100%; left: 0px; right: 0px; top: 0px; width: 10%; background-color: blue; } #container>div {} <html> <div id="container"> <div>up</div> <div>down</div> <d ...

Uploading data using jQuery and submitting it using AJAX techniques

I am currently working on uploading and posting data to a modal window. Although my code works perfectly in IE 10, Chrome, Firefox, Opera, it seems to have some issues in IE versions below 10. Does anyone have any ideas on how I can fix this "bug" or what ...

The issue of Ng-Route not functioning properly on a Node/Express static server

I need assistance with my app.js file that currently directs all requests to pages/index.html. Now I am attempting to utilize Angular to route user requests for '/#/media' by adding the following code: academy.config(function($routeProvider) { ...

What is the reason behind the varying dimensions of images on Chrome compared to Firefox?

I've been working on enhancing my web development skills and decided to create a personal portfolio. During the development process, I focused mainly on Firefox as my browser of choice. One section of the portfolio includes showcasing my skills using ...

Discrepancy in image dimensions between Android and iOS

Currently, I am in the process of building a website and have encountered an issue with the display of images on Android and iOS phones. The image appears differently on an Android Galaxy J-5 compared to an iOS iPhone 6s screen. My goal is to make it look ...

Maximizing image size with dynamic height and automatic width using the NextJS Image Component

I am trying to set my images to have a fixed pixel height and automatic width using object-fit: contain. How can I achieve this with the NextJS Image Component without using layout="fill" so that the intrinsic width of the image (width: auto) is ...

The CSS focus-within and hover properties are not functioning as expected

How can I make the search tags visible (the buttons above the text input field) when the search bar below them is clicked? I've tried using :hover, :focus, and :focus-within, but none of them seem to be working. Can someone help me figure out the issu ...

Move the Bootstrap button to the right side of the div, extending beyond its boundaries

My bootstrap page seems to be experiencing an issue where the buttons within a div are shifted slightly to the right without any clear reason: https://i.sstatic.net/3xlMC.png https://i.sstatic.net/yFLFM.png https://i.sstatic.net/gh686.png The div in qu ...

Having trouble with making a POST request in Node.js using Express.js and Body-parser?

Just starting out with nodejs and currently in the learning phase. I've encountered an issue where my POST request is not functioning as expected. I set up a basic html form to practice using both GET and POST requests. Surprisingly, the GET request w ...

Ensuring form labels are properly aligned with input-group-prepend in Bootstrap

Currently, I am developing a python/django website using bootstrap, and I have encountered an issue that I cannot resolve independently. It has been quite some time since I last worked with python/django/bootstrap, so I may be overlooking something? <fo ...