What is the best way to attach a single block of Javascript code to different div elements without executing them simultaneously?

Running a small ecommerce shop, I have designed product cards using HTML, CSS, and a bit of Jquery for animations. However, a problem arises when clicking the "add to cart" button on any product card as it adds all items to the cart and triggers animations for each one simultaneously. This issue seems to stem from all product cards sharing the same classes/ids, causing the Jquery script to apply the animation to all cards. Is there a way to modify the script to run the animation only once for each product card? Here is the code:

HTML:

    <div class="itemwrapper">
                        <div class="productcontainer">
                            <div class="cardtop" style="
  background: url(images/collar-1.jpeg) no-repeat center center; background-size: contain;"></div>
                            <div class="cardbottom">
                                <div class="cardleft">
                                    <div class="carddetails">
                                        <h1>Multifunction Collar</h1>
                                        <p>$21.99</p>
                                    </div>
                                    <div class="cardbuy"><img class="addtocart" src="images/cart-icon.png" width="85px" height="85px" /></div>
                                </div>
                                <div class="cardright">
                                    <div class="carddone"><img src="images/done.png" width="85px" height="85px" /></div>
                                    <div class="details">
                                        <h1>Multifunction Collar</h1>
                                        <p>Added to your cart</p>
                                    </div>
                                    <div class="cardremove"><img src="images/remove-icon.png" width="85px" height="85px" /></div>
                                </div>
                            </div>
                        </div>
                        <div class="cardinside">
                            <div class="cardicon"><img src="images/info.png" width="30px" height="30px" /> </div>
                            <div class="cardcontents">
                                <table class="cardtable">
                                    <tr>
                                        <th>Details: </th>
                                        <th></th>
                                    </tr>
                                    <tr>
                                        <td colspan="2" style="font-size: 15px">Multifunction collar with different hooks for tags and leash <br />This collar comes with fine high quality soft interior padding which is made exclusively from goat leather.</td>
                                    </tr>
                                    <tr>
                                        <th>Quantity: </th>
                                        <th></th>
                                    </tr>
                                    <tr>
                                        <td><input type="number" id="quantity" name="quantity" min="1" max="5" value="1"></td>
                                    </tr>
                                </table>
                            </div>
                        </div>
                    </div>

JS:

    $('.cardbuy').click(function(){
      $('.cardbottom').addClass("clicked");
    });

    $('.cardremove').click(function(){
      $('.cardbottom').removeClass("clicked");
    });

CSS:

.itemwrapper {
    all: revert;
    width: 300px;
    height: 500px;
    background: white;
    margin: auto;
    position: relative;
    overflow: hidden;
    border-radius: 10px 10px 10px 10px;
    box-shadow: 0;
    transform: scale(0.95);
    transition: box-shadow 0.5s, transform 0.5s;
}

.itemwrapper:hover {
    transform: scale(1);
    box-shadow: 5px 20px 30px rgba(0, 0, 0, 0.2);
}

.itemwrapper .productcontainer {
    width: 100%;
    height: 100%;
}

... (CSS code goes on)

Answer №1

Perhaps something along these lines would be more suitable.

$('.cardbuy').on('click', function() {
    $(this).parent('.cardbottom').addClass('selected') // locate the nearest parent element with the class "cardbottom" and apply the "selected" class
})

The keyword "this" will point to the specific element that was clicked. Your current code is impacting every element with the class "cardbuy".

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

"Let's delve into the world of dynamic variables and Javascript once

As a newcomer to JS, I've scoured countless posts for solutions, but nothing seems to work for me. The issue arises when trying to abstract the code to handle all variables rather than just explicitly expressed values. I am open to alternative method ...

Adjust the content of an iframe based on the size of the screen

Hi there, I'm currently facing an issue with an ad that can't be resized. The support team suggested using two different ads - one for mobile and one for desktop. The dimensions of the ads are 720 x 90 and 300 x 100. I would like the ad to automa ...

Reverse the Angular component to AngularJS

I'm currently working on downgrading an Angular component for use in an AngularJS app. To test this, I created a simple Angular component: // my-test.component.ts @Component({ selector: 'my-test', template: '<h1>Hello Wor ...

The function given to requestAnimationFrame is not being triggered as expected

I have successfully implemented an infinite loop animation using setInterval. However, I want to enhance the performance by switching to requestAnimationFrame(). Unfortunately, the function supplied to requestAnimationFrame() is not being called for some r ...

Unable to retrieve data when utilizing SWR and Context API in Next.js

I'm currently working on fetching data from an API using SWR and dynamically setting the currency based on user preferences through context API. However, I'm facing issues as I am unable to view any data. Can someone please provide assistance or ...

Mist Conceals Celestial View (THREE.JS R76)

I have a cylindrical camera setup with fog to hide the end of the tube. However, I am trying to make the skybox visible through the alpha map sides of the cylinder. The current issue is that the fog is blocking the visibility and I'm looking for a sol ...

Having trouble with JavaScript/JQuery not functioning properly in HTML content loaded using the load() method

My goal is to load an input form from a separate file called new_machine.php into my index.php. This form includes an input with a dropdown that retrieves options from a MySQL database and displays them as anchors. The issue arises when I attempt to manipu ...

Obtain the row ID from a database by selecting checkboxes

I am facing a challenge when trying to remove a row from my MS Access database using checkboxes on my JSP page. Each row in the displayed database has a checkbox, but I am struggling to retrieve the rowId and link each checkbox with its respective row. Any ...

Changing a p element to a div and adding a class in Bootstrap 4.5

To maintain consistency, I prefer using <div class='something'>BIO</div> over <p>BIO</p>. In Bootstrap 4.5, is there a similar class that achieves the same result? I'm not very skilled in CSS, so please forgive me i ...

Stop the continuous AJAX loop or look for an alternative method to retrieve and compare a list of HTML pages

I am in need of a solution to insert a small script onto all of my website pages. The script must include the correct token for each of the 21 different domains I have. However, not all the sites are directly under the 'domain name' but are consi ...

Why am I encountering http://localhost:3000/api/auth/error?error=AccessDenied when implementing Google signin in my Next.js application?

Can someone please assist me in resolving an issue I am facing with my NextJs application using Google signin? Whenever I try to sign in, I get the error message "http://localhost:3000/api/auth/error?error=AccessDenied". Why is this happening? Here is a ...

What is the most efficient method for including a complete date and time in a URL in asp.net mvc?

I am working with a complete datetime object that I want to include as a parameter in a URL. What is the most effective method to ensure it is fully converted to a C# DateTime object without losing any precision? ...

Changing the color of an SVG as I scroll to the bottom of the page

On my React page, I am looking to change the color of an SVG element from black to white at the bottom of the page. Is there a React-specific method for accomplishing this task? The div container located at the bottom of the page is not the parent div fo ...

Selecting an option from a dropdown menu and entering data into a text box

I am currently facing an issue with inserting a value using a text box. The process starts with the admin selecting a category, such as a cellphone brand, from a drop down list. Once the brand is chosen, they will input the cellphone model using a text bo ...

How to successfully embed a podcast episode into an MHT file

I have received an MHT file from Adobe Contribute that contains a flash file for a podcast. The player is supposed to display and then pull the mp3 file, but it seems to be more complex than just a single file. <script type="text/javascript" src="swfob ...

Incorporating arguments within the context of a "for each" loop

I'm attempting to develop a straightforward script that converts RGB-16 colors to RGB-8. The script is functioning properly, but I'm having trouble converting it into a function that can handle two different palettes. Whenever I try using palette ...

What is the reason behind text underline being disabled when using "hidden: overflow" in CSS?

I have a long text string that I want to auto-shorten using CSS with text-overflow: ellipsis, but it's removing the underline from my link. Here is the code: NORMAL .link { font-weight: bold; cursor: pointer; color: black; text-decorat ...

Use jquery ajax to upload an image with a reusable input field

UPDATE: Progress has been made in solving this issue. Please refer to Jquery form no submission to IE7 and IE8. The main task remaining is sorting out the compatibility with IE7 and IE8. I have been utilizing THIS plugin to upload files as email attachmen ...

How to parse JSON in JavaScript/jQuery while preserving the original order

Below is a json object that I have. var json1 = {"00" : "00", "15" : "15", "30" : "30", "45" : "45"}; I am trying to populate a select element using the above json in the following way. var selElem = $('<select>', {'name' : nam ...

Using AJAX to update the value of a div by clicking within a PHP loop

I'm currently working on a php page where I want to dynamically change the content of a div when a specific link is clicked. The links are generated through a loop, and I need to pass multiple parameters via the URL. Since the divs are also created wi ...