Simple method to toggle between elements using jQuery

After creating a script using jQuery to show/hide content when tabs are clicked (which also changes the color of the clicked tab), everything is functioning smoothly. However, I believe there may be a more efficient way to switch between content that allows for easier addition of more tabs. Any assistance in improving this functionality would be greatly appreciated. Feel free to ask if you have any questions or need clarification. Here is a link to the current working version: https://jsfiddle.net/e572s3oq/embedded/result/.

Below is the relevant jQuery code snippet:

    $(document).ready(function() {
  $(".tab:first-child").click(function() {
    $(".content p:nth-child(2)").css('display', 'none');
    $(".tab:nth-child(2)").css('background-color', '#F5F7F7');
    $(".tab:first-child").css('background-color', 'white');
    $(".content p:first-child").css('display', 'block');
  });

  $(".tab:nth-child(2)").click(function() {
    $(".content p:first-child").css('display', 'none');
    $(".tab:first-child").css('background-color', '#F5F7F7');
    $(".tab:nth-child(2)").css('background-color', 'white');
    $(".content p:nth-child(2)").css('display', 'block');
  });

});
body,
html {
  padding: 0;
  margin: 0;
  background-color: #ecf0f1;
}
#wrapper {
  width: 260px;
  margin: auto;
  margin-top: 100px;
}
.tab {
  width: 130px;
  height: 30px;
  font-family: 'Lato', sans-serif;
  font-size: 14px;
  line-height: 30px;
  text-align: center;
  color: #7f8c8d;
  display: block;
  float: left;
}
.tab:hover {
  cursor: pointer;
}
.tab:first-child {
  background-color: white;
}
.tab:nth-child(2) {
  background-color: #F5F7F7;
}
.content {
  width: 260px;
  height: 300px;
  background-color: white;
  overflow: scroll;
}
.content p {
  color: #7f8c8d;
  font-size: 12px;
  font-family: 'Lato', sans-serif;
  margin-top: 8px;
  margin-left: 8px;
  margin-right: 8px;
  margin-bottom: 5px;
}
.content p:first-child {
  display: block;
}
.content p:nth-child(2) {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=wrapper>
  <div class="tab">
    PAGE 1
  </div>

  <div class="tab">
    PAGE 2
  </div>

  <div class="content">
    <p>Content1</p>
    <p>Content2</p>
  </div>
</div>

Answer №1

Here's a simple solution:

$('.tab').click(function() {
    $('.content p').hide();
    $('.tab').css('background-color', '#F5F7F7');
    $(this).css('background-color', 'white');
    $('.content p').eq($(this).index()).css('display', 'block');
});

This script works in the following way:

  • Initially, all p elements within the .content div are hidden by default.
  • The background color of all .tab elements is set to #F5F7F7.
  • When a particular .tab element is clicked, its background color changes to white using $(this).
  • Finally, based on the index of the clicked .tab, a specific p element within the .content div is displayed using .eq().

Demo:

$('.tab').click(function() {
    $('.content p').hide();
    $('.tab').css('background-color', '#F5F7F7');
    $(this).css('background-color', 'white');
    $('.content p').eq($(this).index()).css('display', 'block');
});
body, html {
    padding:0;
    margin:0;
    background-color:#ecf0f1;
}
#wrapper {
    width:260px;
    margin: auto;
    margin-top:100px;
}
.tab {
    width:84px;
    height:30px;
    font-family:'Lato', sans-serif;
    font-size:14px;
    line-height: 30px;
    text-align: center;
    color:#7f8c8d;
    display: block;
    float: left;
    background-color: #F5F7F7;
}
.tab:hover { cursor:pointer; }
.tab:first-child { background-color: white; }
.content {
    width:260px;
    height:300px;
    background-color:white;
    overflow: scroll;
}
.content p {
    color:#7f8c8d;
    font-size: 12px;
    font-family:'Lato', sans-serif;
    margin-top:8px;
    margin-left:8px;
    margin-right:8px;
    margin-bottom:5px;
}
.content p:first-child {
    display:block;
}
...
        <p>Lorem ipsum dolor sit amet... (Additional content added for demonstration purposes)</p>
    </div>
</div>

I made some CSS adjustments and expanded the HTML content in the example above. Hopefully, this clarifies things for you.

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

The navbar does not dictate the views

Greetings lovely individuals I've been grappling with this issue for a while now and it seems I can't quite crack it on my own... I'm hopeful that you can assist me. My objective: A functioning navigation bar controlled by PHP in an MVC pat ...

Converting data to a JSON string using jQuery's AJAX method

When I use document.write() for JSON data, it works fine outside of the AJAX call, but not inside the .done() function. I even tried removing the dataType: 'json' parameter, but it still didn't work. $.ajax({ url: "http://api.wundergrou ...

The AJAX call returned undefined, leading to an error when trying to access the length property

I've scoured various resources to find a solution for this issue, but unfortunately, I haven't had any luck with implementing the code. The problem lies with my JSON parser function, which is designed to construct a table based on data received ...

Meshes that overlap with transparency features

Could anyone help me with this issue I'm facing? I have a scenario where I am rendering multiple meshes in Three.JS with different solid colors and transparency. However, these meshes are overlapping and the colors are blending together in the overlap ...

Transform my Curl script into a NodeJS app

I'm trying to replicate the functionality of a curl command within my NodeJS application, but I am facing some difficulties. Any guidance on how to achieve this would be greatly appreciated. curl -H "Authorization: bearer $TOKEN" If I already hav ...

Ways to solely cache spa.html using networkfirst or ways to set up offline mode with server-side rendering (SSR)

I am facing an issue with my application that has server-side rendering. It seems like the page always displays correctly when there is an internet connection. However, I am unsure how to make Workbox serve spa.html only when there is no network available. ...

Ways to manipulate a div tag with CSS even when it lacks a class or ID attribute

Hey there! I've got this snippet of HTML code that I'm working with: <div class="template-page-wrapper"> <div class="templemo-content-wrapper"> <div class="templatemo-content"> <div c ...

Some pages are receiving images from the CDN, while others are not

I am encountering some challenges while troubleshooting an issue on a website. The CDN (content delivery network) is functioning properly on some pages but not on others. Initially, I suspected a typo in the path, but that does not seem to be the case. F ...

Hiding labels in an HTML document can be achieved by using CSS

Recently, I've been working on a code that relies on a specific Javascript from Dynamic Drive. This particular script is a form dependency manager which functions by showing or hiding elements based on user selections from the forms displayed. Oddly ...

Angular 2 template format standard

Every Angular 2 example I encounter seems to place the template within the component decorator. import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: '<h1>Hello world</h1>' }) e ...

Innovative CSS trick for styling checkboxes alongside non-related content

The CSS checkbox hack demonstrated below assumes that the content is a sibling of the checkbox. By clicking on the label, the content will toggle. Check out the DEMO here <input id="checkbox" type="checkbox" /> <label for="checkbox"> Toggle ...

An issue has arisen where I encounter the error message: 'TypeError: callback is not a function', even though the function appears to be continuing to run successfully

Encountering an error message 'TypeError: callback is not a function' while attempting to execute a particular function. Here is the code snippet in question: const api = require('axios'); getData(printData); async function getData ...

Changing the dimensions of a flyer inside a jQuery popup

I've encountered a recurring issue for which I have not found a solution despite scouring numerous resources for answers. The problem involves the incorrect rendering of tiles within a jQuery Modal that contains a Leaflet map generated by a rails app ...

Group the elements of the second array based on the repeated values of the first array and combine them into a single string

I have a challenge with two arrays and a string shown below var str=offer?; var names = [channelId, channelId, offerType, offerType, Language]; var values =[647, 763, international, programming, English]; Both arrays are the same size. I want to creat ...

Is it possible to utilize hCard for semantic markup exclusively for a business's contact information?

Can hCard be used to markup a business's contact information without including a personal name? According to the hCard guidelines, a name is required in the format (e.g. John Doe): . I am specifically trying to mark up just a business's contact d ...

JQuery post request not providing the expected response after posting

I have a post request var prodId = getParameterByName('param'); var pass = $('#password1').val(); $.post("rest/forget/confirm", { "param" : prodId, "password" : pass }, function(data) { ...

When utilizing Express and passport, an error occurs stating that req.isAuthenticated is undefined

After successfully setting up a backend express server in the past few hours, I decided to implement authorization by following a tutorial. The login functionality works perfectly, but when attempting to access /authrequired (a restricted page that require ...

How come Selenium is stopping me from extracting text content from the "ul" and "li" elements?

This piece of code represents my work: from selenium import webdriver from selenium.webdriver.common.keys import Keys # For being able to input key presses import time ...

Ordering tables according to the last column using jQuery

Despite trying various solutions provided in other discussions, I have been unable to get the table to display in descending order based on the Weight Score column. Here is a reference of the table: <table align="center" border="1px" cellpadding="5" id ...

During the build process, Next.js encounters difficulty loading dynamic pages

My Next.js application is utilizing dynamic routes. While the dynamic routes function properly in development mode, I encounter a 404 error when deploying the built app to Netlify. https://i.stack.imgur.com/45NS3.png Here is my current code setup: In _ ...