What is the best way to implement jQuery slide toggle functionality with a class?

I found a code snippet on that I used to create an FAQ panel in HTML. However, the issue is that the code is set up with an ID, so I can only use it once. I actually want to be able to use it multiple times for different sections of my website.

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script> 
$(document).ready(function(){
  $(".flip").click(function(){
    $(this).next(".panel").slideToggle("slow");
  });
});
</script>

<style type="text/css"> 
.panel,.flip
{
padding:5px;
text-align:center;
background-color:#e5eecc;
border:solid 1px #c3c3c3;
}
.panel
{
padding:50px;
display:none;
}
</style>
</head>
<body>

<div class="flip">Click to slide the panel down or up</div>
<div class="panel">Hello world!</div>

</body>
</html>

Answer №1

see the demo here

javascript code:

$(function(){
    $('a.toggle').click(function(){
        $('.myContent').stop().slideToggle(500);
        return false;
    });

});

HTML snippet:

<a href="#" style="background-color: #99CCFF; padding: 5px 10px;" class="toggle">CLICK HERE</a>

<div>
    <div class="myContent" style="background-color: #99CCFF; padding: 5px 10px;">We have optimized the javascript so that all the code is based on jQuery.
    </div>

    <div class="myContent" style="background-color: #CCCCFF; padding: 5px 10px;">jQuery was used to optimize all the javascript code in this tutorial.
    </div>
</div>

Answer №2

modify the id to class and then incorporate class selectors in css and jQuery

<div class="flip">Click to slide the panel down or up</div>
<div class="panel">Hello world!</div>
<div class="flip">Click to slide the panel down or up</div>
<div class="panel">Hello world!</div>
<div class="flip">Click to slide the panel down or up</div>
<div class="panel">Hello world!</div>

CSS

.panel, .flip {
    padding:5px;
    text-align:center;
    background-color:#e5eecc;
    border:solid 1px #c3c3c3;
}
.panel {
    padding:50px;
    display:none;
}

and then

$(document).ready(function () {
    $(".flip").click(function () {
        $(this).next('.panel').slideToggle("slow");
    });
});

Demonstration: Fiddle

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

Attempting to implement a feature that will enable a blank row at the end of an input table with the help of

I'm currently working on a form that allows users to click a button to add a blank row to the bottom of a table. The issue I'm facing is that when I click the button, it redirects back to my index.php page instead of simply adding the row to the ...

Issue with PassportJS and Express 4 failing to properly store cookies/session data

I have a situation with my Express 4 app using Passport 0.3.2. I've set up a passport-local strategy, and it's successfully retrieving the user information when the /session endpoint is provided with a username and password. The issue arises whe ...

Scrollable navigation bar at the bottom styled with Bootstrap

I've been trying to find an answer to this question online but haven't had any luck. I designed a responsive bottom navbar with Bootstrap, but I'm encountering an issue when listing multiple items using the <li> tag - it creates a new ...

After resolving a promise, what is the process for loading a Next.js App?

Seeking guidance on implementing the code snippet below using Next.js. I suspect there is an issue with Next.js not being able to access the window object without being within a useEffect(() => {}) hook. When switching back to regular React, the code ...

Troubleshooting the issue of AJAX failing to upload a picture file to both the

I'm facing an issue where my script is not uploading the picture to the server and inserting it into the database when I use ajax submit for some reason. However, if I submit the form with php action="file.php" it works fine. Here are my ajax script a ...

Updating the Navbar in React Routing does not happen automatically, but it does refresh when the page is refreshed

Currently, I am using vanilla React with React-Router for my project. One of the issues I am facing is detecting whether a user on the page has a token, indicating their logged-in status. While setting up routes for Login/Register/Logout functionalities, ...

How do I retrieve a nested object element based on the value of a specific field in Mongoose?

Below is the teamModelSchema schema that I am working with. var teamMemberModelSchema = new mongoose.Schema({ "email": { "type": String, "required": true, "min": 5, "max": 20 }, "name": { "type": String ...

Clicking on a radio button will update the text within a span

Can jQuery AJAX be used for this task? I am looking to update the content of a <span> when a radio button is clicked. <input class="unitSelectInches" type="radio" name="units" value="inches" />Inches <input class="unitSelectCenti" type="ra ...

"Quotes are essential in Javastript syntax for specifying string values

I need to implement a JavaScript syntax to generate unique URLs for each image. The Robohash website provides random robot images based on different URL endings. I tried the code below, but it seems like ${props.id} is being interpreted as part of the UR ...

Comparing the transmission of a form through Ajax versus PHP

Just have a few quick questions. I've got this form that I'm sending using jQuery's Ajax function, and it's doing exactly what I want it to do. Even if JavaScript is disabled, the form will still be sent through server-side processing, ...

The background image of Jquery chosen plug-ins is not visible on Firefox browser

Typically, the selected plug-in functions seamlessly across a variety of browsers, including older versions of Internet Explorer. However, I recently discovered an issue with the latest version of Firefox and the plug-in. The dropdown menu image has disa ...

Adjust the size of icon passed as props in React

Below is the component I am working on: import ListItemButton from '@mui/material/ListItemButton'; import ListItemIcon from '@mui/material/ListItemIcon'; import Tooltip from '@mui/material/Tooltip'; const MenuItem = ({data, o ...

Receive emails: using the require() function with ES Module

After following the react-email documentation, I encountered an error when trying to run the yarn email command: $ email dev --port 3001 ***\node_modules\ora\index.js:65 if (process.platform === 'win32') { ...

Running Jest tests on an ajax request leads to an error involving the undefined $ variable

We are currently in the process of integrating Jest testing into our existing project, but we have encountered some difficulties. Specifically, we are trying to test the functionality of the following function: // Send picture function sendESGPIC(results) ...

In React Native, I must include individual radio buttons for each item retrieved from the API

When I select a radio button on mobile, all radio buttons get selected instead of just the one clicked. Here is the current behavior: https://i.stack.imgur.com/qRJqV.jpg The expected behavior is to have only the clicked radio button selected, like in thi ...

Turning On/Off Input According to Selection (Using jQuery)

<select name="region" class="selection" id="region"> <option value="choice">Choice</option> <option value="another">Another</option> </select> <input type="text" name="territory" class="textfield" id="territo ...

What is the most efficient method for converting a string into an object in a Node.js environment?

This code seems to be functioning correctly, but it appears quite lengthy. Is there a more concise approach to achieve the same result? The primary objective here is to extract a sorting parameter from an HTTP query and use it to sort a collection in Mong ...

Unable to load app.component.html on Plnkr

Plunker link: Click here to view the Plunker https://i.sstatic.net/QXZDv.png Resource Directory: https://i.sstatic.net/yS423.png app.ts File Content: import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/plat ...

Child component not receiving disabled state from Angular 8 FormControl

In my code, there is a unique custom input that I have defined: <nivel-servico-slider formControlName="fornecedor_a"></nivel-servico-slider> This custom input has all the necessary properties as outlined in Angular's guide for c ...

Graphql query using $http.post is unsuccessful

I successfully made a request for the code below, but I am encountering an issue where I am not receiving any data back. The "preview" tab of the request in Chrome simply displays "Error Not Found". Interestingly, when I try the same query in GraphiQL, i ...