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

Obtaining the value of a checkbox with React

I have a form with two input fields (email, password) and a checkbox. The code for the form is shown below: <Box component="form" onSubmit={handleSubmit} noValidate sx={{ mt: 1 }}> <TextField margin="normal" required ...

When trying to update a MySQL database, the ampersand is appearing as &amp;amp; instead of the expected &

Currently, I am in the process of creating an administrative section that will allow for easy management of information displayed on the main website. This section will enable users to add, update, and delete content using just one page. Most of my script ...

Why does `npm init react-app` automatically select yarn as the default package manager? (npm version 6.14.5)

After executing the command npm init react-app, I noticed that npm automatically selects yarn as the default package manager for the newly created app. To resolve this, I followed the steps provided in How Do I Uninstall Yarn to remove yarn from my system. ...

Tips for ensuring a watcher only runs once in each digest cycle, regardless of how many times the property is modified

I am facing an issue with my function $scope.render() that relies on the value of $scope.myProperty to render a chart. Whenever myProperty changes during a digest cycle, I need to ensure that $scope.render() is called only once at the end of the digest cyc ...

Modifications made to the process module in one file are not reflected in a different file

It seems that the process module in NodeJS is not global, resulting in changes made to it in one module not reflecting in other modules. To confirm my findings, I wrote a small piece of code. Here is the snippet: server.js import app from "./app.js& ...

What could be the reason for the component failing to update even after modifying the object's properties?

I have come across some related threads on Stack Overflow, but they only briefly mention using the spread operator. But why should we use it? In the code below, I am trying to update the firstName property of the user object, which is a state, when clicki ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the ...

I am looking to retrieve a sophisticated/nested JSON data using jQuery

I need some assistance in fetching specific JSON object data. Specifically, I am looking to extract the name, poster image URL, size of the second backdrop image, and version number. As a newcomer to JSON, I was wondering if there is an easy way for me to ...

Changes in a deep copy of an object in a child component are directly reflected in the parent object in VueJS

Let's begin by discussing the layout. I have a page dedicated to showcasing information about a specific company, with a component Classification.vue. This component displays categories of labels and the actual labels assigned to the current company. ...

What is the best way to eliminate the alert message "autoprefixer: Greetings, time traveler. We are now in the era of CSS without prefixes" in Angular 11?

I am currently working with Angular version 11 and I have encountered a warning message that states: Module Warning (from ./node_modules/postcss-loader/dist/cjs.js): Warning "autoprefixer: Greetings, time traveler. We are now in the era of prefix-le ...

Struggling to fix errors within a nested div element?

I'm currently utilizing AngularJS to perform basic form validation. Below is the current code snippet: <form name="myForm" id="form_id" method="post" novalidate> <div class="form-group"> <label for="myField_input" class="c ...

Setting a value to a FormBuilder object in Angular 2 with Typescript

During my use of Reactive form Validation (Model driven validation), I encountered an issue with setting the value to the form object on a Dropdown change. Here is my Formgroup: studentModel: StudentModel; AMform: FormGroup; Name = new FormControl("", Va ...

Tips for refreshing a component after fetching a new page using the useQuery function

Attempting to retrieve and display data from my custom API using axios and react-query's useQuery. The API incorporates pagination, and I have implemented a table with an option to select the page that displays the current data. Everything functions c ...

Using Ajax, the script triggers calls upon detecting keyup events on various input fields, each

I'm encountering issues while attempting to solve this logic puzzle. The page contains multiple fields and the goal is to store the input values in the database when the user finishes typing. Here's the code snippet: var debounce = null; ...

What is the method for activating a validation of a child component from a parent component during the submission process in Angular 4

I have a scenario where I have multiple child form components included in a parent component. Each child component contains its own form group, and I need to validate all child forms when the user clicks on submit in the parent form. How can I trigger val ...

Is it possible to assign a property name using a string during the creation of an object?

Can an object property be named directly within the object declaration instead of afterwards? For example, this syntax works: var name = "foo"; var obj = {}; obj[name] = "bar"; // obj.foo === "bar" But is there a way to define it inside the object it ...

Obtaining zip files using AngularJS

Upon entering the following URL in my browser, I am prompted to download a file: My goal is to download this file using an AngularJS HTTP request. I have created a factory for this purpose, but unfortunately, the download is not successful. Even though ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

How come the use of a timeout causes the this variable to seemingly lose its reference?

What is the reason why this: myelements.mouseenter(function() { clearTimeout(globaltimeoutvar); globaltimeoutvar = setTimeout(function() { var index = myelements.index(this); console.log(index); // -1 }, 150); }); Returns -1, while this: m ...

Sending various values from ASP.NET to a javascript function

I am currently attempting to pass multiple parameters (eventually 4 total) into a JavaScript function from my ASP.NET code behind. In the ASCX file, I have defined the function as follows: function ToggleReportOptions(filenameText, buttonText) { /*stuff ...