How to remove an event listener that was added within a function in JavaScript?

I am encountering an issue while trying to remove an event listener that was created inside a function. Oddly enough, it works perfectly when I move the event listener outside of the function. See the example below:

<body>
<div id='myDiv'></div>
<button type='submit' onclick='rel()'>RemoveEventListener</button>

<script>
function Mouse() {
    myDiv.addEventListener('click', cK);
    function cK() {
        alert('You've clicked on myDiv!');
    }
}
function rel() {
    myDiv.removeEventListener('click', cK);
}
Mouse();
</script>
</body>

Answer №1

If you have a variable ck that is defined within the scope of the Mouse function, it will not be accessible inside the rel function. To make it available in both functions, move the variable declaration outside of the Mouse function:


function cK() {
    alert('You clicked on myDiv!');
}
var ck;
function Mouse() {
    myDiv.addEventListener('click', cK);
}
function rel() {
    myDiv.removeEventListener('click', cK);
}

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

Mastering the Art of Promises in RXJS Observables

After thoroughly researching SO, I stumbled upon numerous questions and answers similar to mine. However, I suspect that there might be gaps in my fundamental understanding of how to effectively work with this technology stack. Currently, I am deeply enga ...

Switch the URL of the current tab to a different one by clicking a button within a Chrome extension with the help of JavaScript

Could someone assist me in changing the current tab URL to a different website, such as , using a chrome extension? Here is my JavaScript code: chrome.tabs.query({active: true, currentWindow: true}, function(tabs) { var tab = tabs[0]; console.log(tab.url) ...

Is it Possible to Alter the Title Attribute in AngularJS with ng-class?

My website currently displays an image that updates based on the user's selection from a dropdown menu. The title of the image is set to "test", but I need it to display a different message depending on which image is being shown. Can this be achieved ...

There is an array present with data filled in, but unfortunately, I am unable to retrieve specific elements

As I work on my WordPress 4.7.2 website, I find myself making an AJAX call. The PHP function handling this call returns an array using wp_json_encode(). When I view the data array in the success callback of the AJAX function, everything looks just as expec ...

Unveiling Elements as You Scroll Within a Specified Area

I have implemented a jQuery and CSS code to reveal my contact form as I scroll down the page. However, I am facing an issue with setting a specific range for displaying the element while scrolling. Currently, I have only managed to handle the scrolling dow ...

Tips for modifying and refreshing data in a live table with JQuery

One challenge I'm facing is figuring out how to transfer the data from a dynamic table back into input fields when clicking on the edit button of a specific row. Additionally, I need to update that particular row based on any changes made to the value ...

A guide on transforming JSON data into HTML using Rails

I'm struggling with parsing JSON on a webpage. My webpage is designed with circles, where clicking on a circle triggers a call to the controller to retrieve specific information from a database and display it as graphs and text. The issue I'm fa ...

Cypress and Cucumber collaborate to reinitialize the requests within Next Js

In my upcoming project with Next.js, I am utilizing Cypress for testing a specific page. The objective is to validate two scenarios: 1. Successful outcome and 2. Error handling when a user encounters an issue. Before(() => { return void cy.server() ...

Having trouble with HTML - JavaScript function not processing responseText?

On my website, there is a button array that displays the position of a robot by reading a text file using a php/ajax combo. The script initially sets all buttons to the same color and changes the color of the button to represent the robot's position. ...

Tips for triggering functions when a user closes the browser or tab in Angular 9

I've exhausted all my research efforts in trying to find a solution that actually works. The problem I am facing is getting two methods from two different services to run when the browser or tab is closed. I attempted using the fetch API, which worke ...

Ensure that grid rows occupy the least amount of space possible

I'm relatively new to grid layout and I've encountered a challenge that has me stuck. Here's what I have so far: codepen And this is the relevant part of the grid: grid-template: 'img date' 'img head' 'img s ...

Receiving updates on the status of a spawned child process in Node.js

Currently, I'm running the npm install -g create-react-app command from a JavaScript script and I am looking to extract the real-time progress information during the package installation process. Here is an example of what I aim to capture: https://i ...

Toggle the visibility of a table column based on user selection in Vue.js

I am having issues with displaying and hiding based on checkbox click events. Can anyone assist in identifying the mistake? When clicking on an ID, it should hide the ID column. Similarly, clicking on "first" should show/hide based on checkbox clicks, and ...

Expiration Alert: SSL Certificates for HERE Links will expire shortly

Our SSL certificates for the following URL's are approaching expiration: *.base.maps.ls.hereapi.com geocoder.ls.hereapi.com Do you have any information on when these URLs will be updated with new certificates? ...

Creating a FusionCharts time series with a sleek transparent background

Currently, I am attempting to achieve a transparent background for a time-series chart created with FusionCharts. Despite trying the standard attributes that usually work on other chart types and even hardcoding a background color, none of these seem to af ...

Swapping out a subarray within an array containing objects with a fresh array consisting of objects

Here is the structure of my data document: { "_id": "6287a6c5975a25cc25e095b0", "userName": "Robot", "projectName": "TestProject", "projectTypeName": "fixed project", "pro ...

Exploring Event Listeners in the World of JavaScript and/or jQuery

Is there a more sophisticated way to monitor the execution of a specific function in JavaScript or jQuery? Instead of waiting for an event like $('#mything').click(function(){ //blah }), I prefer to be notified when a particular function is trig ...

Issue with BeautifulSoup(page.content,'html.parser') not returning accurate content during web scraping

While attempting to scrape data from the AJIO website, I encountered an issue where the content retrieved by Python did not match what I saw when inspecting the exact webpage. It appears that there is some JavaScript code present on the page which dynamica ...

Unveiling the Power of AngularJS for Parsing JSON Data

A list of images is being generated in a table-like structure using the code snippet below. Each image represents a cell in this table, with its ID specifying its row and column position. <ul> <li class="row"> <ul> & ...

Learning how to use Express.js to post and showcase comments in an HTML page with the help of Sqlite and Mustache templates

I am facing a persistent issue while trying to post new comments to the HTML in my forum app. Despite receiving various suggestions, I have been struggling to find a solution for quite some time now. Within the comments table, each comment includes attrib ...