What could be causing the mouseenter event listener to function properly on the initial grid-item but fail to work on the remaining items?

When I hover over any of the grid items, I want the addToCartBar to only show on that specific item. However, currently it is only working on the first item. What am I missing?

Below is the relevant ejs code:

<div class="main-cont">  
                <div class="grid-container">
                    <div class="grid-item grid-item-1">
                        <div class="add-to-cart">ADD TO CART</div>
                            <div class="item-img">
                                <img src="/NikeTiempo.png" alt="">
                            </div>
                            <div class="card-text">
                                <h5>Category</h5>
                                <h3 class="product-name">Product Name</h3>
                                <h3 class="price">$200</h3>
                            </div>
                    </div>        

                    <div class="grid-item grid-item-2">
                        <div class="add-to-cart">ADD TO CART</div>
                            <div class="item-img">
                                <img class="rotated-img" src="/AdidasAce.png" alt="">
                            </div>
                            <div class="card-text">
                                <h5>Category</h5>
                                <h3 class="product-name">Product Name</h3>
                                <h3 class="price">$200</h3>
                            </div>
                    </div>
                    <div class="grid-item grid-item-3">
                        <div class="add-to-cart">ADD TO CART</div>
                        <div class="item-img">
                            <img src="/NikeTiempo.png" alt="">
                        </div>

// more grid-items follow...

And here is the JS code:

// //Hover Effect On Grid-Item
let cardItems = document.querySelectorAll('.grid-item');
let addToCartBar = document.querySelector('.add-to-cart')

for (let cardItem of cardItems) {
    cardItem.addEventListener('mouseenter' , () => {
        addToCartBar.style.display = "flex"
    })
}

I understand that the above code iterates through the array of cardItems and should display the addToCartBar for each one individually, but it's not working as expected. Any advice or suggestions would be greatly appreciated. Thank you.

Answer №1

An issue arises when you continuously change the display property of the button in the first card item every time due to the line

let addToCartBar = document.querySelector('.add-to-cart')
. This code snippet selects the first matching element by traversing the DOM. To achieve the desired outcome, you need to query inside each cardItem individually as shown below:

// Hover Effect On Grid-Item
let cardItems = document.querySelectorAll('.grid-item');

for (let cardItem of cardItems) {
    cardItem.addEventListener('mouseenter' , () => {
      let addToCartBar = cardItem.querySelector('.add-to-cart')
      addToCartBar.style.display = "flex"
  })
}

Answer №2

Regarding the code provided, I have an answer for your query:

The querySelector() method in the Document object retrieves the first element that matches the specified selector or group of selectors within the document. It returns null if no match is found.

By using querySelectorAll(), you can apply event listeners to multiple elements instead of just one.

You also have the option of utilizing the hover CSS selector to streamline your code. This can be done by creating a separate CSS file and linking it to your JavaScript file, or directly inserting the snippet into your code as shown below:

.add-to-card:hover {
  // Add desired behavior here
}  

For more information on CSS selectors, you can refer to this resource.

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

How to ensure that the $window.location.reload(true) function is executed only once in an Ionic/Angular application

I need help modifying this code so that it resets my app only once when it goes to the homepage instead of continuously reloading. What changes can I make in the JavaScript to achieve this? .controller('HomeCtrl', function ($scope, $window) { $s ...

When a form added by jQuery is submitted, the associated JavaScript does not run as expected

After clicking a button on my page, jQuery removes one form and replaces it with another. However, when I try to submit the second form, the associated JavaScript does not execute as expected. Instead of running the JavaScript function, the form submissio ...

Complete a function after a promise has been fulfilled

Is it possible to include an unlink function in the resolve of a promise? import { unlink } from 'fs/promises'; import { createReadStream } from 'fs'; import csv from 'csv-parser'; const keywords = []; const collectKeywords ...

PassportJS ensuring secure authentication across all routes

Currently, I am implementing passportJS to secure my API Endpoints within an Express application. So far, the following code is functioning properly. app.get("/route1", passport.authenticate('basic', { session: false }), (req, res) => { ...

Angular model does not bind properly to Bootstrap 3 DateTimePicker after 'dp.change' event

I am currently implementing the Bootstrap 3 DateTimePicker plugin by eonasdan. While everything seems to be functioning correctly, I have encountered an issue with binding the selected date within the input field to Angular's ng-model. Whenever I make ...

Node.js (Express), passport.js, mongoose.js, and Android app all have in common the HTTP Error 307 - Temporary redirect

I am currently constructing a REST Api using Node.js (Express.js and Moongose.js). I have a single post route that takes JSON data and redirects it to the signup page (/app/signup) if the user is a first-time user (not found in the database), or to the log ...

How to smoothly reveal a popup form in jQuery mobile on an iOS device by scrolling up

A popup containing a form was created using jquery mobile. Below is the code for the form. <div data-role="popup" id="popupDetailles" data-theme="a" data-overlay-theme="b" style="width:100%;" data-transition="pop" class="ui-corner-all ui-popup ui-body ...

Looking to display information in a column-by-column format using ng-grid within Angular JS

The data I have is structured like this: $scope.myStudentData = {"Moroni":{"id":"1","grade":"A"},"Tiancum":{"id":"2","grade":"B"}} However, the grid requires a different format: $scope.myGridOptions = [{"details":"id", "Moroni":"1", "Tiancum":"2"},{"det ...

Preserve the video's aspect ratio while adjusting the browser size

I am currently developing a video editing tool and facing a challenge in maintaining the aspect ratio of `16:9` when resizing the screen both horizontally and vertically. While I have successfully achieved the expected behavior for horizontal resizing and ...

A problem arises when trying to showcase the content in a responsive manner on the hamburger menu, particularly when viewing on mobile

As a newcomer to web development, I decided to challenge myself by building an E-Commerce website to enhance my skills. To ensure mobile responsiveness, I opted for a hamburger menu to hide the navbar content. However, despite resizing working flawlessly, ...

Exploring the ins and outs of utilizing the Context API within Next JS 13 alongside server-side components

Can Next JS 13 handle server-side data fetching and then pass it to the Context API? In my scenario, I need to retrieve user information using a token on the server side, but then transfer it to the Context API for potential usage throughout the applicati ...

Start the jQuery animation only when the ajax information differs

I am using setInterval to create a timer that runs every 20 seconds. It utilizes jQuery's ajax function load() to populate the toparticles div with data from another URL on the site. After the data is successfully loaded, it applies a jQuery highlight ...

Looking to boost the efficiency of jQuery when choosing multiple option lines within a selection tag

Looking to optimize the speed of a jQuery line that selects a tag with thousands of option tags. Is there a faster solution than the current one? Perhaps using plain javascript instead? The code is slow and unresponsive when used with a select tag name cha ...

Ways to retrieve the highest date value in an array

I'm running into an issue where I am trying to find the maximum day in an array of dates, but for some reason it keeps returning either Invalid Date or null. I'm not sure what's going wrong. Do you think I should convert the values to a diff ...

Triggering Events with Angular Checkboxes

I'm having trouble getting a console log to trigger when the user checks one of the checkboxes. The script is working fine for everything else, but checkbox clicks are not registering any events. Any suggestions on why this might be happening? (Just ...

The createAsyncThunk function seems to be failing to trigger in the redux toolkit implementation

Currently, I am tasked with developing an application in React, and the reference application I am using as a guide is located at Below is the code snippet I have been working on in the resourceSlice.js file: import axios from 'axios'; const { c ...

Utilize the express error handler to manage exceptions within a .catch block

I am currently working on developing an application using Express along with the q promise library. I am also utilizing Winston for logging and restler for making HTTP requests. My main goal is to ensure that when an asynchronous error occurs in my code a ...

Vue data() attribute lacking proper assignment of props

I am currently developing a Vue component that needs to update the list of restaurants based on dynamically selected filters by the user. In order to achieve this, I need to modify the filteredRestaurants in the data() method of my Vue component. However, ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

Receiving an error when Node.JS spawns a Python process: `JSONDecodeError("Expecting value", s, err.value) from None`

I am attempting to launch a Python process (App.py) from a node.js file (index.js). In the script index.js, the python script App.py is spawned and passed an argument params in the form of a JSON object. App.py then extracts the value from the uParams ele ...