Add a class individually for each element when the mouse enters the event

How can I apply the (.fill) class to each child element when hovering over them individually?

I tried writing this code in TypeScript and added a mouseenter event, but upon opening the file, the .fill class is already applied to all elements. Why is this happening?

class Rate {
    private stars : any ;

    constructor(){
        this.init()
    }

    init(){
        this.stars = document.querySelectorAll("#rating div");
        for (let i = 0; i < this.stars.length; i++){
            this.stars[i].setAttribute('count', i);
            this.stars[i].addEventListener("mouseenter",this.fill(this.stars[i]))

        }
    }
    fill(elm){
        elm.classList.add("fill")
    }
}

let a   =  new Rate()

HTML:

<div id="rating" class="rating">
<div ><i class="ion-android-star"></i></div>
<div ><i class="ion-android-star"></i></div>
<div ><i class="ion-android-star"></i></div>
<div ><i class="ion-android-star"></i></div>
<div ><i class="ion-android-star"></i></div>
</div>

Compiled JS:

var Rate = /** @class */ (function () {
    function Rate() {
        this.init();
    }
    Rate.prototype.init = function () {
        this.stars = document.querySelectorAll("#rating div");
        for (var i = 0; i < this.stars.length; i++) {
            this.stars[i].setAttribute('count', i);
            this.stars[i].addEventListener("mouseenter", this.fill(this.stars[i]));
        }
    };
    Rate.prototype.fill = function (elm) {
        elm.classList.add("fill");
    };
    return Rate;
}());
var a = new Rate();

Answer №1

In order to properly execute the action, it is necessary to pass a function instead of executing the fill immediately in the `init` functions. A simple way to achieve this is by using an arrow function.

init(){
    this.stars = document.querySelectorAll("#rating div");
    for (let i = 0; i < this.stars.length; i++){
        this.stars[i].setAttribute('count', i);
        this.stars[i].addEventListener("mouseenter", () => this.fill(this.stars[i]))

    }
}

Answer №2

It's not possible to use addEventListener in that manner, as the function will be executed.

Instead, try this approach:

class Rating {
    private stars: any;

    constructor() {
        this.initialize();
    }

    initialize() {
        this.stars = document.querySelectorAll("#rating div");
        for (let i = 0; i < this.stars.length; i++) {
            this.stars[i].setAttribute('count', i);
            this.stars[i].addEventListener("mouseenter", this.fill.bind(this));
        }
    }

    fill(e) {
        e.target.classList.add("fill");
    }
}

let ratingInstance = new Rating()

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 conceal a button before printing and have it reappear once the printing process is finished?

I have a button on my webpage with the id "print_req" that is used to trigger a JavaScript function for printing the page. I want this button to be hidden during the printing process and then reappear afterwards, so it does not show up in the printed docum ...

Mapping JSONP responses for jQuery UI autocomplete

Attempting to implement jqueryUI autocomplete. After alerting the response, it shows: ([ { "id": "test", "label": "test", "value": "test" } ]); However, when trying to map the result, the dropdown remains empty. Here is the code being used: <script> ...

Discovering a specific element using jQuery

I am trying to work with a div structure like this: <div class="country"> <div class="cty_popover"> <p>TITLE</p> <ul> <li>NAME 1</li> <li>NAME 2</li> ...

Experiencing Limitations with Node.JS node-hbase Scan Functionality, Unable to Retrieve More than 1000

I am facing an issue while trying to retrieve records from an HBase table in Node.JS using the node-hbase module, which connects to the rest server. I am able to fetch the first batch of records successfully, but I am struggling to get the next set of re ...

Fixing the "Cannot find name" error by targeting ES6 in the tsconfig.json file

I recently started learning AngularJS through a tutorial. The code repository for the tutorial can be accessed at this link. However, upon running npm start using the exact code provided in the tutorial, I encountered the following error: Various TS2304 e ...

Retrieving a single item from an array of objects with the help of body parser

I need assistance with sending an array of objects to a post route in my express app. Here is my form (written in ejs format): <form action="/archiveList/<%= list._id %>" method="POST"> <input type="hidden" name="list" value = <%= items ...

AngularJS/Ionic: Issue with HTTP GET requests not completing within a specified timeframe

Attempting to populate options with specific values instead of undefined, but encountering a delay in retrieving the values after the select box has finished loading. https://i.stack.imgur.com/SpEFP.jpg To illustrate, here is the HTML code snippet: < ...

Sending PHP output data to jQuery

Trying to implement this code snippet /* Popup for notifications */ $(document).ready(function() { var $dialog = $('<div></div>') .html('message to be displayed') .dialog({ ...

Avoid invoking a TypeScript class like a regular function - _classCallCheck prevention

I am currently developing a TypeScript library that needs to be compatible with all versions of JavaScript. I have noticed that when calling a class in TS without using new, it does not compile properly, which is expected. In ES6/Babel, a class automatica ...

Seeking assistance with basic Javascript/Jquery for Ajax on Rails 3 - can anyone help?

I've been diving into JavaScript and hit a roadblock. At the moment, I have a very basic gallery/image application. My goal is to create a functionality where clicking on an image will lead the user to a URL stored in my model data using AJAX. Additi ...

How to handle an unexpected keyword 'true' error when using the `useState` hook in React?

Trying to set the open prop of the MUIDrawer component to true on user click is causing an error stating "Unexpected keyword 'true'" import React, { useState } from "react"; import { withRouter } from "react-router-dom"; impo ...

Using Vue components alongside vanilla JavaScript code

I am currently working on integrating Vue.js into an existing project that does not utilize Vue. Unfortunately, I have been unable to find any resources or documentation on how to create a Vue component with an API that can be accessed by external code out ...

Error Alert: "Invariant Violation" detected in a TypeScript program utilizing React

When attempting to implement the react-collapse component in my TypeScript application along with a custom d.ts file, I encountered the following error: Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a ...

Ensure each list item is directly aligned when swiping on a mobile device

Looking to make a simple horizontal list swipeable on mobile devices with tabs that snap from tab to tab, activating the content for the active tab immediately. The desired effect is to swipe directly from one tab to the next without having to click separ ...

Learn how to define an object with string keys and MUI SX prop types as values when typing in programming

I want to create a comprehensive collection of all MUI(v5) sx properties outside of the component. Here is an example: const styles = { // The way to declare this variable? sectionOne: { // What type should be assigned here for SXProps<Theme>? } ...

How do @material-ui/core and @types/material-ui interact with each other?

Exploring a sample project that utilizes material-ui. Upon inspecting the package.json file, I noticed the inclusion of the following packages: { ... "dependencies": { "@material-ui/core": "^1.4.1", ... }, "devDependencies": { "@types ...

Inspecting a union type with a TypeScript property validation

I have defined a union of two types in my code. Here are the definitions: type Generic = { subtype: undefined, user: string, text: string } type Other = { subtype:'message', text: string } type Message = Generic | Other; Within my co ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

Verify if an express module has a next() function available

Is there a method to check if there is a function after the current middleware? router.get('/', function(req, res, next){ if(next){//always returns true } }); I have a function that retrieves information and depending on the route, thi ...

The Typescript compiler is unable to locate the module './lib'

I'm currently integrating the winston-aws-cloudwatch library into my TypeScript server-side application. If you want to replicate the issue, I have provided a SSCCE setup on GitHub. Here are the details: index.ts import logger from './logger& ...