Tips for implementing a single function across multiple HTML classes using JavaScript

For the past few days, I've been struggling with a JavaScript issue as a newcomer to the language.

$(document).on('click', '.content-click', function(){
    $(".content-click span").toggleClass("clicked"),
    $(".content-view").toggleClass("viewed");
    $(this).show();
});
.content-click {
    display: block;
    width: 100%;
    height: 2rem;
    padding: 0.375rem 0.75rem;
    font-size: .75rem;
    font-weight: 500;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: 0.25rem;
    cursor: pointer;
}

.content-click p {
    display: inline;
    margin: 0;
}

.content-click span {
    width: 10px;
    height: 10px;
    position: relative;
    top: 5px;
    float: right;
    vertical-align: middle;
    background: url(../img/arrow.png) no-repeat;
    transition: all 0.3s ease;
    transform: rotate(0deg);
}

.content-click span.clicked {
    transform: rotate(90deg);
} /*button click styling */

...

<div class="container">
            <div class="content-click" style="margin:.25rem;">
                <div id="content-1">
                    <p>First Item list...</p>
                    <span></span>
                </div>
            </div>
            <div class="content-view">
                <div id="view-1">
                    <p>Description...</p>
                </div>
            </div>

            ...

</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
In this scenario, I implemented buttons that reveal a text area or description when clicked by the user. However, it got me thinking - if I eventually have 100 items, would I need to assign 100 different IDs for each item?

I noticed that when using the same class name as the .toggleClass target, clicking on one button causes all items with the same class to show their descriptions. It's a bit confusing, but please bear with me as I navigate this learning curve.

Answer №1

To ensure that only the next description expands when clicking an item, you must maintain the scope of your click event.

Check out the code snippet below:

$(document).on('click', '.content-click', function(){
    $(this).find("span").toggleClass("clicked"); // Finds the child element 'span'
    $(this).next().toggleClass("viewed"); // Selects the next sibling element
    $(this).show();
});
.content-click {
    display: block;
    width: 100%;
    height: 2rem;
    padding: 0.375rem 0.75rem;
    font-size: .75rem;
    font-weight: 500;
    line-height: 1.5;
    color: #495057;
    background-color: #fff;
    background-clip: padding-box;
    border: 1px solid #ced4da;
    border-radius: 0.25rem;
    cursor: pointer;
}

.content-click p {
    display: inline;
    margin: 0;
}

.content-click span {
    width: 10px;
    height: 10px;
    position: relative;
    top: 5px;
    float: right;
    vertical-align: middle;
    background: url(../img/arrow.png) no-repeat;
    transition: all 0.3s ease;
    transform: rotate(0deg);
}

.content-click span.clicked {
    transform: rotate(90deg);
} /* Styling for button click */

.content-view {
    display: block;
    width: 100%;
    height: 0;
    border: 0px solid #ebebeb;
    box-sizing: border-box;
    margin-top: 0rem;
    margin-bottom: 0rem;
    position: relative;
    border-radius: .25rem;
    padding: 0;
    font-size: 0;
    font-weight: 500;
    opacity: 0;
    transition: all 0.2s ease;
}

.content-view::after {
    content: '';
    width: 10px;
    height: 10px;
    border-top: 1px solid #ebebeb;
    border-right: 0px solid #ebebeb;
    border-bottom: 0px solid #ebebeb;
    border-left: 1px solid #ebebeb;
    position: absolute;
    left: 95%;
    top: 0%;
    margin-top: -6px;
    margin-left: -6px;
    transform: rotate(45deg);
    background-color: #fff;
}

.content-view.viewed {
    height: auto;
    border: 1px solid #ebebeb;
    margin-top: .25rem;
    margin-bottom: 1rem;
    font-size: .75rem;
    padding: 1rem;
    opacity: 1;
} /* Styling for description text area */
<div class="container">
            <div class="content-click" style="margin:.25rem;">
                <div id="content-1">
                    <p>First Item list...</p>
                    <span></span>
                </div>
            </div>
            <div class="content-view">
                <div id="view-1">
                    <p>Description...</p>
                </div>
            </div>
            <div class="content-click" style="margin:.25rem;">
                <div id="content-2">
                    <p>Second Item list...</p>
                    <span></span>
                </div>
            </div>
            <div class="content-view">
                <div id="view-2">
                    <p>Description...</p>
                </div>
            </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

Answer №2

Avoid relying on ids to locate elements in such cases.

To begin, capture the event object.

$(document).on('click', '.content-click', function(event){

Next, utilize it to access the clicked element.

var $clicked = $(event.currentTarget);

… then utilize methods like parent and find to navigate to the related element you wish to interact with.

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

What is the best way to configure the default selected value order in a jQuery select2 remote select box?

After customizing the select2 plugin to display default selected values, I encountered a problem when editing sessions. While creating a session and selecting multiple speakers from the dropdown, they were displayed as selected. However, when editing anoth ...

Error: The call stack has reached its maximum size while running an npm install

Attempting to execute npm install, encountered the following console output: npm ERR! Linux 4.8.0-27-generic npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "install" npm ERR! node v6.9.1 npm ERR! npm v3.10.8 npm ERR! Maximum call stack size exceeded npm ...

Tips for adding data to an array while iterating through an object:

I have a task of looping through object results fetched from an API and pushing them into an array. historys: any = []; Here is how I am attempting to loop through the objects: Object.keys(response['orderdetail']).forEach(function(index, key) ...

Getting started with CSS and HTML: Tips and Tricks for Beginners

Seeking advice on how to enhance my web designing skills, particularly in starting point and techniques. Currently, I am familiar with HTML and CSS, but have been primarily using pre-made templates for building websites. I aspire to be able to transform ...

Implementing proper data return in MVC4 through an Ajax call

When using ajax to call an action in a controller, the code may result like this: $.ajax({ type: "POST", url: "getUserInfo.json", data: "", success: function (data) { if (data.resultInfo.resu ...

A collection of jQuery objects that consist of various DOM elements as their properties

Seeking a more concise and potentially more streamlined approach using jQuery. I have an object called lbl which represents a div. Inside this div, there is a span tag that contains the properties firstName and lastName of the lbl object. Here's how t ...

The `appendTo` function in Ajax is used to swap out the current element

I have been working on sending form data to a Servlet using JQuery and then receiving the response from the same JQuery. Check out the code snippet below. <%-- Document : index Created on : Feb 23, 2015, 8:18:52 PM Author : Yohan --% ...

Learn how to effectively showcase various components by leveraging the new react-router-dom v6.0.0 alongside react-redux

My issue is that when I click on a link to render different components, the URL updates but the UI remains unchanged. No matter which item I click on to render, the same thing happens. I've tried numerous solutions to fix this problem without success. ...

Having trouble with Javascript in getting one-page scroll navigation to work?

Hey there, I am working on creating a one-page scroll navigation with some basic javascript to add a smooth animation effect that takes 1 second as it scrolls to the desired section. However, I seem to be experiencing an issue where it's not functioni ...

What could be causing the alteration of my JSON data when sent through a WEB.API Ajax request?

Before Ajax Call: "{ "UnitOfMeasureRelatedUnitDataInbound": [ { "Name": "test", "Active": true, "UnitOfMeasureTypeID": "dd89f0a0-59c3-49a1-a2ae-7e763da32065", "BaseUnitID": "4c835ebb-60f2-435f-a5f4-8dc311fbbca0", "BaseUnitName": null, ...

Linking promises to eliminate nesting

Hi everyone, I am currently working on chaining promises in my code. The initial HTTPS call returns an array of URLs successfully. After that, I loop through them to obtain a JSON object for each one. I am wondering if there is a way to reduce nesting in ...

Having trouble with test coverage in Mocha using Blanket?

I have a Node application that I want to test and generate a coverage report for. I followed the steps outlined in the Getting Started Guide, but unfortunately, it doesn't seem to be working correctly. In my source code file named src/two.js: var tw ...

Tips for submitting a form using javascript while preventing the default action

Looking for a way to submit a form in Javascript and prevent the default action? Let's explore how you can achieve this. Initially, my HTML form with the ID "contact_form" had an input element like so: <input id="contact_send_msg" type="submit" val ...

One way to change the cursor CSS property is by dynamically altering it based on scrolling behavior. This involves modifying the cursor property when scrolling

I'm attempting to adjust the cursor property within an Angular function. The issue I'm facing is that when I begin scrolling the webpage, the cursor changes to a pointer, but when I stop scrolling, it remains as a pointer. I've attempted to ...

What are some techniques for obtaining the second duplicate value from a JSON Array in a React JS application by utilizing lodash?

Currently, I am tackling a project that requires me to eliminate duplicate values from a JSON array object in react JS with specific criteria. My initial attempt was to use the _.uniqBy method, but it only retained the first value from each set of duplicat ...

The cart total variable in Vuejs is coming back as NaN

I'm currently in the process of creating a cart system using vuejs and I've encountered an issue where my total variable is displaying NaN instead of calculating the total price of all products. Below is the function responsible for calculating ...

When executing a Javascript POST request to a PHP script, it succeeds when running on

I have a simple code that works fine on my website when the PHP file is linked as "/phpcode.php", but it fails to retrieve data when I place the JavaScript request on another site and use the full link. I am currently using GoDaddy as my hosting provider. ...

Is there a way for me to move a user from one room to another room?

My friend and I both have our own rooms in a session. When I want to send him a message, I need to switch his room to the same one where I am. This is the code snippet for creating my own room with static sessions: socket.on('chat-in', function ...

In Python, carry out a Google search and specifically retrieve the content from the top 10 results

Currently, I am in the process of developing a script that will conduct a Google search based on a specified keyword and then extract only the content from the top 10 resulting URLs. Please note: By "content," I am referring to the specific information re ...

An issue arose during the installation of nodemon and jest, about errors with versions and a pes

Currently, I am facing an issue while trying to set up jest and nodemon for my nodejs project. My development environment includes vscode, npm version 6.13.7, and node version 13.8.0. Whenever I try to install nodemon via the command line, the console disp ...