Utilizing jQuery to create a dynamic onClick navigation tab that fetches body content

I am working on a page with 3 tabs at the top that need to change their styling when clicked. I have successfully implemented this using the .toggleClass('active') function and applying CSS to the 'active' class.

Now, I need to display related content in the body of the page when each tab is clicked. Here's what I have so far:

<ul>
    <li class="active">Primary</li>
    <li>Secondary</li>
    <li>Tertiary</li>
</ul>
<div class="tabs">
    <div class="slate">Content1</div>
    <div class="slate">Content2</div>
    <div class="slate">Content3</div>
</div>

When an li is clicked, it applies the 'active' class (working), but I also want it to show the content from the corresponding div within the 'tabs' container. For example, clicking on 'Primary' should display the content from the first child in the 'tabs' div.

Thank you!

Answer №1

If you are able to modify your HTML code, you can assign IDs to the li elements and use the same ID values as class names for the tab contents. This way, you can easily target the specific ID to toggle the corresponding tab content:

$('li').click(function(){
  $(this).addClass('active').siblings('li').removeClass('active');
  $('.slate.'+this.id).show().siblings('.slate').hide();
});
li{list-style:none;}
.slate{display:none;}
.slate.active{display:block}
li.active{color:red;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>

  <li id='primary' class="active">Primary</li>
  <li id='secondary'>Secondary</li>
  <li id='tertiary'>Tertiary</li>

</ul>
<div class="tabs">

  <div class="slate primary active">Content1</div>
  <div class="slate secondary">Content2</div>
  <div class="slate tertiary">Content3</div>

</div>

Answer №2

Identify the content panels using IDs or classes that indicate which tab they are associated with. Then toggle the visibility of the content panels when a tab is clicked.

HTML:

<div class="tabs">
    <div class="slate tab-1">Content1</div>
    <div class="slate tab-2">Content2</div>
    <div class="slate tab-3">Content3</div>
</div>

JS:

$("tab-selector").on("click", function () {
    var index = $(this).index() + 1;
    $("div.slate").hide();
    $("div.tab-" + index).show();
});

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

Having an issue with Javascript onclick not updating div content upon first click

Having difficulty getting content from one div to another on the initial click. Some of my code: <a href="#" onClick="goPage1();">Feed</a> Function being called: function goPage1(){ $("#feed").html(""); get_jsonp_feed(); $("#con ...

Positioning Bug in FF/IE with Absolute Placement

It appears that Chrome is the only browser displaying my code correctly. While testing in Firefox and Internet Explorer, I have noticed that my position:absolute is being affected by the border size, unlike in Chrome where it remains unaffected (which is ...

Ways to design an overlapping image

In the process of creating a product information page, I am facing an issue where clicking on a product should display the product image, description, and recommended products below. However, for some products, the layout gets disrupted as the product imag ...

Identify HTML elements within a textarea or text input using JavaScript while also accommodating the common special characters ">" and "<"

Is there a way to accurately detect HTML tags in textarea or text input fields before submitting a form? While it may seem straightforward to use regular expressions like /<\/?[^>]*>/gi.test(str) for this purpose, the challenge arises when de ...

Using Jquery to open a dialog box and then utilizing ajax to trigger the opening of

Currently experiencing some difficulties with jQuery and AJAX in trying to open a second dialog box within another dialog box. Below is the jQuery code: $( "#dropdownuser" ).dialog({ autoOpen: false, show: "blind", height : 600, ...

Transforming the indicator of the React responsive carousel to full-width rectangles

I am working on customizing the indicators to appear rectangular and cover the full width based on the length of the images, similar to this example: https://i.sstatic.net/j4yov.png However, I am currently facing an issue where the divs are always displa ...

Creating a cohesive look with a background gradient and image simultaneously

Short Version Is it possible to have both a background color with a linear gradient and a background image at the same time? Long Version I have styled a table with a vertical linear gradient in the header, as shown below: table { white-space: no ...

Tips for adding jQuery UI styling to elements generated dynamically

I have a challenge with generating text fields using jquery while applying jquery ui styling to the form. The issue is that the dynamically created elements do not inherit the css styles from jquery ui: let index = 0; $('#btn_generate').on(& ...

AngularJS refresh the display of ngRepeat items

I'm currently displaying products and their details using ngRepeat in a table. In addition to that, I have created a custom directive: .directive('onFinishRenderFilters', function ($timeout) { return { restrict: 'A', ...

Creating a combined Email and Password form field in a single row using Bootstrap

Recently, I decided to explore bootstrap. I am looking to implement email/password validation in one row on my rails app: email? | password? | OK Currently, I have a functioning code for displaying only an email field and an OK button in one row: email? ...

The color type input is not responding to the onChange event

I have been searching a lot and exploring answers on Stack Overflow, yet I have had no luck. I am trying to retrieve the color value when the color is changed in an input field. Here is the code I am using, could you please assist me in finding out why it ...

Can someone guide me on how to verify a user's input by comparing it against a predefined set of strings in JavaScript?

I am new to JavaScript and still learning, so please bear with me. I have a unique task of creating multiple voucher codes, each with a specific redeemable amount. When a user purchases a voucher and enters the code in a text field, I need JavaScript to v ...

Adjusting webpage background with JavaScript

I've been struggling with this for the past six hours and can't seem to get it right. I've checked out various solutions on Stack Overflow, but nothing seems to work. What am I missing here?!? My html5 page doesn't have a background an ...

Sorry, we couldn't find the page you were looking for. The request method used was GET and the request URL was http://127.0.0.1:

I've previously reported this error without success, so I'm providing more details now. I am new to coding and recently started a Django & Python project, but encountered some issues. Despite three weeks of troubleshooting, the problems persist. ...

Cross-domain AJAX requests do not allow cookies to be set

I have implemented a JavaScript on my webpage to send a POST request to a webservice located at . The response from the webservice sets cookies that are necessary for authentication. Accept-Ranges:bytes Access-Control-Allow-Credentials:true Access-Contro ...

Tips for implementing Animation.css in Angular version 1.5.8

I have successfully added the ngAnimate dependency to my AngularJS project: var app=angular.module('testApp',['ngRoute', 'ngAnimate']); I have also included the animation classes in my animation.css file: .slide-animation.n ...

Struggling to get a price calculator up and running efficiently

The code I have should be functioning, however, when I insert it into the code module in the Divi theme on WordPress, it doesn't work. Interestingly, when I try it in a notepad, it works perfectly fine but fails to function on the website itself. () ...

Switching between Login Form and Register Form in VueJS template

Recently, I attempted to switch between the 'Login Form' and 'Register Form' using code that I found on codepen Flat HTML5/CSS3 Login Form. While the code functioned properly on its own, when integrated into a Vue Template, the form fai ...

Create a dynamic HTML table as the page loads

Customize for vhinn This is the desired output: I am currently attempting to dynamically create an HTML table on pageload using variables retrieved from a database. Here is a simple example of HTML code: http://jsfiddle.net/jdv590/daCum/1/ Code snippet ...

The body element is not positioned at the top of the webpage in the HTML/CSS layout

I'm running into an issue with my HTML/CSS. It seems like my body tag has unexpectedly acquired a margin-top of 10px... However, I've searched high and low but can't seem to figure out how to remove it. This is something that has never happe ...