Unable to remove EventListener after clicking on element

Hey guys, I need to remove the "mouseenter" event after an element is clicked. I tried something like this but the event is not being removed. Can someone please tell me why? Below is the code snippet where I am attempting to do this in the enter() function:

TypeScript:

class Rate {
    public stars: any;

    constructor() {
        this.init()
    }

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


    }

    enter(elm) {
        this.dochange(elm.target);
        let item = elm.target;
       // console.log(this);
        elm.target.addEventListener("click", function () {
            document.getElementById("note").innerHTML = elm.target.getAttribute('count');
            document.removeEventListener("mouseenter",function () {
                alert()
            })
        })
    }


    dochange(el) {

        for (let i = 0; i < this.stars.length; i++) {
            //  console.log(el.stars[i].getAttribute("count"))
            if (this.stars[i].getAttribute("count") > el.getAttribute("count")) {
                this.stars[i].classList.remove("fill")
            } else {

                this.stars[i].classList.add("fill")
            }
        }
    }
}

let obj = new Rate();

Compiled JavaScript :

var Rate = /** @class */ (function () {
    function Rate() {
        this.init();
    }
    Rate.prototype.init = function () {
        this.stars = document.querySelectorAll("#rating div");
        var self = this;
        for (var i = 0; i < this.stars.length; i++) {
            this.stars[i].setAttribute('count', i + 1);
            this.stars[i].addEventListener("mouseenter", this.enter.bind(self));
        }
    };
    Rate.prototype.enter = function (elm) {
        this.dochange(elm.target);
        var item = elm.target;
        // console.log(this);
        elm.target.addEventListener("click", function () {
            document.getElementById("note").innerHTML = elm.target.getAttribute('count');
            document.removeEventListener("mouseenter", function () {
                alert();
            });
        });
    };
    Rate.prototype.dochange = function (el) {
        for (var i = 0; i < this.stars.length; i++) {
            //  console.log(el.stars[i].getAttribute("count"))
            if (this.stars[i].getAttribute("count") > el.getAttribute("count")) {
                this.stars[i].classList.remove("fill");
            }
            else {
                this.stars[i].classList.add("fill");
            }
        }
    };
    return Rate;
}());
var obj = new Rate();

Answer №1

Make sure you are using removeEventListener correctly by referring to the documentation at this link.

It is important to note that you should add and remove listeners from the same element, not from different elements like a div and document. Use removeEventListener on the same element where you called addEventListener, such as this.stars[i].

Additionally, if an element has multiple listeners for the same event type, specify which listener you want to remove by passing the correct reference to removeEventListener, just like with this.enter.

this.stars[i].addEventListener("mouseenter", this.enter);
this.stars[i].removeEventListener("mouseenter", this.enter);

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

Choose the initial division within the table and switch the class

Here is a straightforward request - I need to employ jquery to target the first div with the class of "boxgrid captionfull" within the tr element with the classes "row-1 row-first," and switch the class to 'active_labBeitrag'. <table class="v ...

Challenges encountered with preventing form submissions

I have completed similar tasks multiple times in the past, but for some reason, I am encountering a different outcome now. This is my first attempt at using Laravel, and the project I am working on is very basic. Despite that, the issue seems to be related ...

Error: The method area is not supported for this.mesh.geometry

Recently, I've been experimenting with JavaScript, Three.js, and Leapmotion. To enhance my program, I decided to incorporate the leap widgets library which can be found here. However, after investing numerous hours into this project, I encountered a ...

Tips for building a basic particle system with THREE.js

I am looking to create a simple particle system that forms a circle around the name of the site in the middle. The particles should move around in the circle, "die off," and then get recreated. While I am new to three.js, I have attempted to find a solut ...

I am looking to generate div elements using JavaScript to avoid the tedious task of individually creating numerous divs

Instead of manually typing out multiple div tags in the HTML, I would like to dynamically generate them using JavaScript and display them on the page. Below is an attempt at achieving this, but it appears to not be functioning correctly. var arr = {}; f ...

The challenge of storing GeoJSON data within SQLite database using Cordova

Below is a snippet of code that I am working with: var json_data = document.getElementById("json_data").value; console.log(json_data); tx.executeSql('INSERT INTO floodmaps VALUES (?,?,?)', [1, flodMapName, json_data], function(tx ...

What is the process for assigning default values to dynamically generated form elements?

I have been working on building a single-page application (SPA) using JavaScript and jQuery. During the process, I encountered an issue with a dynamic form. The user is able to add specific fields as needed, but if they don't generate and utilize all ...

Issue with Promise function not resolving in the context of javascript and Wit.ai

Currently, I am in the process of updating the functions in my messenger/wit.ai chat bot to transition from using callbacks to promises. The initial format functions properly: ['buildScenario'](sessionId, context, cb) { var trendChoice = s ...

Inside the function() in angular 2, the value of 'this' is not defined

I've integrated a UIkit confirmation modal into my app. However, I'm encountering an issue when trying to click the <button> for confirmation. The this inside the function is showing up as undefined. Here's the snippet of code in quest ...

Is there a way to set up automatic switching to a minimized browser window when receiving an alert, even if you are currently using a different window like Outlook or Explorer?

Is there a way to automatically switch to a minimized browser window from a different program window (such as Outlook or Explorer) when an alert is received on a specific tab? I'm looking for a Javascript/Jquery solution. I've attempted the foll ...

Confirm the validity of a web address

At the moment, I am utilizing Angular 5 and attempting to validate a URL in the following manner: Here is the HTML code snippet: <div class="form-group col-sm-6"> <input formControlName="s_url" type="url" class="form-control" id="kk" placehold ...

Tips on scrolling down to find the text you're looking for

I attempted to scroll downwards in my application's window using the following JavaScript code: ((JavascriptExecutor) driver).executeScript("windows.scrollBy(0,500)"); Additionally, I tried to ensure a specific element is in view with this script: ...

What is the best way to automatically post to Slack at regular intervals?

In order to provide users with the option to choose when they receive information from my API, such as daily at 5PM or every Friday at 5PM, I have a configuration page. Once users set their preferred time, I want to send them a Slack message at that specif ...

execute field function prior to sorting

Currently, I am building a graphql server in express and using a resolver to modify my fields based on user input from the query. The issue arises from the transformer function returning a function. My goal is to sort the results by a field determined by ...

Performance issues may arise in React styled-components when the state changes frequently during mousemove events

My current challenge involves implementing a parallax animation using react hooks and styled-components, but I am facing performance issues. The constant rerenders of components seem to be causing janky animations rather than smooth ones. Here are the sty ...

What methods can I employ to implement global variables within a VueJS component?

How do I access global variables within a VueJS component? I'm attempting to retrieve the `url` variable in the fetch function within the `methods` section, but it seems to be causing issues. var products = []; var url = '/data-set.json'; ...

Setting a validation message for a Vuejs username input while enforcing a maximum character limit

<script> export default { name: "Register", props: { msg: String, }, }; </script> <style scoped> * { box-sizing: border-box; } div { padding: 0; margin: 0; font-family: system-ui; } .red { color: red; } <template& ...

Creating a custom loading spinner featuring your logo

Hello, I am looking to create a custom loading spinner using CSS, JS or any other method with my logo. I have the logo in PNG, GIF, and SVG formats and would like to use it for long site loads, image loads, or any other loading processes within my Vue3 pro ...

Ways to display and conceal login and logout buttons in the AppBar based on the login status of another component through the utilization of local storage

Within my App component, there is a rendering of the MyAppBar component featuring Login and Logout buttons. Additionally, the App component renders a Login form component which contains a button responsible for adding user information to local storage, sim ...

Attempting to send a POST request, only to be informed by the form that it is devoid of

I have been struggling with this problem for some time now. I implemented the category_create_post functionality in the categoryController, and everything seems to be set up correctly. I also configured the category_form.ejs to accept user input. However, ...