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

Performing a GET call within the configuration settings of AngularJS

I found a similar question here but unfortunately it didn't solve my issue. I am currently using Angular-UI's Google Maps API, which requires configuration as follows: .config(function(uiGmapGoogleMapApiProvider) { uiGmapGoogleMapApiProvider ...

How does NodeJs handle ongoing tasks and processes seamlessly?

One interesting concept is the Event Loop, which accepts callbacks and executes them as needed. As far as I understand, this operates on a single thread event loop, meaning only one callback is executed at a time. Consider the following example: setInterv ...

Using globs to specify files for gulp.src

I'm facing a challenge in setting up a glob array for my JavaScript concatenation build task within the Gulp workflow. The file structure I am working with looks like this: ├── about │ └── about.js ├── assets ├── contact â ...

Error Encountered While Building Flask Application

Whenever I try to submit the form, an error pops up and I can't see the flash message even though it's added to my database: werkzeug.routing.BuildError BuildError: ('/contacts', {}, None) Here are my methods: @app.route('/conta ...

How to position slides in the center using react-slick

I'm having difficulty achieving vertical centering for an image in a react-slick carousel implementation. The issue can be seen here. https://codesandbox.io/s/react-slick-playground-o7dhn Here are the problems identified: Images are not centered: ...

Troubleshooting a Codeigniter issue with CSRF and jQuery ajax

Having trouble with posting data using ajax? I keep running into an error related to CSRF and despite my efforts, I have not been able to find a solution. Can someone please assist me with this issue? Here is the error message I am consistently receiving: ...

Error: The function updateElement does not exist

Currently, I am facing an issue while trying to update an element in an array by adding an object as a property. This requires user interaction through a modal where the form is filled and then added as a property for a specific node. However, I encountere ...

The amazing feature known as "CSS3 background-clip"

Seeking a solution for restricting a background image to the text within an h2 element using -webkit-background-clip. Wondering if -moz-background-clip functions in the same way as -webkit-background-clip. As it currently only works in webkit browsers, it ...

TypeScript properties for styled input component

As I venture into TS, I’ve been tasked with transitioning an existing JS code base to TS. One of the challenges I encountered involves a styled component in a file named style.js. import styled from "styled-components"; export const Container ...

Ascending to the Peak within a div

<script type="text/javascript"> $(document).ready(function(){ updateContent(); }); function updateContent(){ $('#mainDiv').load('home.php', function(){ scrollToTop(); }); } ...

What about employing the position:fixed property to create a "sticky" footer?

I've come across various methods for creating a sticky footer, such as Ryan Fait's approach found here, another one here, and also here. But why go through the trouble of using those techniques when simply applying #footer{position:fixed; bottom ...

The Vue template syntax utilizes double curly braces for incrementing values within must

Embarked on learning Vue.js recently and I am intrigued by the unusual behavior in my simple code. I cannot seem to figure out what is going wrong. I am attempting to increment a counter inside mustache syntax, but something strange is happening with this ...

What is the best way to make a drop down menu list appear when I click on the parent li, and then show the sub li using JavaScript?

I have a code that includes an image, HTML, and CSS code. Can anyone please tell me how I can set up a drop-down menu list to open the sub <li> elements when I click on a parent <li> using JavaScript? You can see the appearance of the code in t ...

The request to send JSON POST to REST encountered a 400 Bad Request

I've encountered an issue while sending a POST request from JQuery with some data. Unfortunately, when I try to execute it through my JavaScript code, I receive a 400 Bad Request error and the REST service fails to fire. Out of curiosity, I decided t ...

Modify CSS using Javascript by targeting the class of ".modalDialog > div {}"

I am currently working on a project that involves creating a Modal Layer using CSS. I have successfully implemented the modal layer, but now I need to figure out how to change the width from the default 400px to something else when I open it with Javascrip ...

Determine the overall width of a JSX element

Is there a way to retrieve the width of a JSX.Element? In a traditional setup, I would typically use something like: const button = document.createElement('button'); document.body.appendChild(button) window.getComputedStyle(button).width However ...

A guide on updating object values within an array using map in React

Is there a method to calculate the total sum of specific values from an array of objects? Example array: const exampleArray = [ {item_id: 1, quantity: "3"}, {item_id: 2, quantity: "5"}, {item_id: 3, quantity: "2"} ] In this case, I want to add up the qua ...

Show the Vue.js template in a Laravel Blade view

I have been struggling to integrate a Vue.js component into a Laravel blade file. Despite researching tutorials and Stack Overflow solutions, I have not been able to resolve the issue. Below is the template that I want to display: <template> < ...

FirebaseError: The type 'Hc' was expected, but instead, a custom Yc object was provided

I've encountered an issue while attempting to perform a batch entry. The error I'm facing involves passing an array in a .doc file. Interestingly, this approach seems to work perfectly fine on another function where I pass an array into a .doc us ...

Convert a two-column layout on the web into a single-column layout for mobile devices, featuring dynamic

Is there a way to style this diagram with CSS that will work on IE11 and all major browsers? It seems like Flexbox doesn't support dynamic height. Do I need separate left and right columns for larger viewports and no columns for smaller viewports? ...