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

Slow rotation in CSS styling

.badge { -webkit-transform-style: preserve-3d; -webkit-perspective: 1000; position: relative; } .back, .front { position: absolute; -webkit-backface-visibility: hidden; -webkit-transition: -webkit-transform 1s ease-in; width: ...

Using jQuery to remove the 'active class' when the mouse is not hovering

I recently came across this amazing jQuery plugin for creating slide-out and drawer effects: However, I encountered a problem. I want to automatically close the active 'drawer' when the mouse is not hovering over any element. The jQuery plugin c ...

How can JavaScript be used to prevent pinch and zoom functionality on Google Maps?

In my project, I am utilizing Google Maps but I want to disable the zooming effect on the map. To achieve this, I have disabled the zoom control using zoomControl: false,. However, this modification only applies to desktops and laptops as they do not suppo ...

Are there numerous instances of jQuery references both preceding and following the use of '$.noConflict'?

Managing a large project with thousands of PHP files can be challenging, especially when dealing with conflicting jQuery references that hinder the implementation of a desired plugin. Consider this scenario: <html> <head> ...

Is it possible to maintain the sidebar while eliminating the scrolling JavaScript?

Looking to recreate the image display style on Facebook where pictures appear in a lightbox format. The challenge I'm facing is figuring out how they manage to have the sidebar with no visible scroll bar inside... If you want to see this for yourself ...

Challenges when upgrading from Ext JS 3 to Ext JS 4

I am looking to upgrade my code from Ext JS 3 to Ext JS 4. I used the Ext.Updater class in Ext JS 3, but I cannot seem to locate a similar functionality in Ext JS 4. Can anyone provide assistance with this transition? ...

Creating HTML code from a website by utilizing XML

As someone who is not a developer and doesn't have much knowledge about java, I am seeking advice on potential solutions to achieve the following. This web hosting service enables users to retrieve data from their XML spreadsheets and embed them anyw ...

What is the best way to conceal selected options in a MUI multiselect in the select field?

I'm currently working with a MUI multiselect feature to allow for the selection of multiple options from a dropdown menu. However, I am facing an issue where I do not want the selected options to be visible within the dropdown field. Is there a way to ...

The Google Maps API swipe feature on mobile devices is causing issues with screen scrolling

When users visit my website on mobile, they encounter a situation where Google Maps suddenly covers the entire page, preventing them from scrolling away. This is because swiping up or down only moves the map view within Google Maps, instead of scrolling th ...

Fetching data from an external server using an Ajax request to access the contents of a CSV file

I am trying to access the data from a csv file using ajax with the following URL: "". However, I encountered some errors along the way. When attempting to retrieve the data, I received CORS error. $.ajax({ url: 'http://real-chart.finance ...

Playing sound files on Angular using Howler.JS

I am currently trying to incorporate the ability to play an mp3 file within a Cordova + Ionic hybrid app. The sound file is located at: www/sounds/dubstep/sound.mp3 I am attempting to play the file from a service placed in /www/scripts/services/global.j ...

Dealing with code issues in Subscription forms using AJAX and JQuery

Currently, I am independently studying jQuery and grappling with the Mailchimp Opt-In form code. Despite various existing queries on this topic, I am curious about why my own implementation, as a beginner in jQuery, is not functioning correctly. My intenti ...

Fade out at varying speeds

As I delve into CSS3 animations, I have been experimenting with some example code. Here is the link to the code: http://jsfiddle.net/chricholson/z7Bg6/67/ I am curious about how to adjust the duration of animations when un-hovering. Currently, it seems th ...

What is the best way to display a page within a div when clicking in Yii?

I'm trying to use the jQuery function .load() to load a page into a specific div. Here's my code: <a href="" onclick="return false;" id="generalinfo"> <div class="row alert alert-danger"> <h4 class="text-center">Gen ...

Struggling to retrieve JSON data within the code

Recently, I've been receiving a JSON data from Microsoft cognitive services but unfortunately, I'm encountering difficulties incorporating it into my code. Is there something that I might be doing incorrectly? I attempted different approaches su ...

Different ways to shuffle the arrangement of divs

Forgive me if this seems like a simple query, but I am struggling with it. Essentially, what I want to achieve is to randomize the positioning of the items, where item 1 can adopt the style of item 3 (or 2 or 4), item 2 can take on the style of 1, 3, or 4, ...

Upon including the enctype attribute as "multipart/form-data" in my form and submitting it, the form redirects to a different page

My website has two main pages: The first page is admin.php <?php session_start(); if (!isset($_GET['page'])){ $_GET['page'] = 'home'; }//end if include_once(dirname(__FILE__)."/function.php"); ?> <?ph ...

I am looking to extract a specific value from my JSON file

I need to extract specific values from a JSON file. For example, if the JSON file contains id, name, and lastname, I am interested in extracting the id value. fs.readFile("user.json", function (err, data) { if (err) throw err; console.log(data. ...

How should I manage objects that are passed by reference in the context of functional programming?

Lately, I have been experimenting with some code in an attempt to delve deeper into functional programming. However, I seem to have hit a snag. I am struggling with handling an object. My goal is to add key-value pairs to an object without reassigning it, ...

Shut down two modal windows and then open one anew

I am facing an issue with fancybox where I need to open 2 modals of a plugin and then close 2 and open 1 again... For example: closing 2 modals and opening 1 modal again... http://jsfiddle.net/g3R75/1/ I have tried the following code but it doesn't ...