Using .addEventListener() within a function does not successfully generate the intended event listener

For a while, my program ran smoothly with the line

canvas.addEventListener("click", funcName, false);
. However, I recently realized that at times I needed to replace this event listener with another one:
canvas.addEventListener("click", difFuncName, false);
. To address this, I created four functions in my JavaScript files - two to add these event listeners and two to remove them.

What I observed was that when the function adding the new event listener calling difFuncName successfully added the listener and later executed the remover function without any issues. However, the initial event listener, which was now being called within a function, seemed to not work anymore.

Prior to moving the first listener inside its own function, my code only had a function containing:

canvas.removeEventListener("click", funcName,false);
, which also failed to remove the event listener as desired - resulting in both event listeners executing their respective functions.

To verify the execution of each function, I inserted console.log("checking"); into all four functions and confirmed that they were indeed being executed.

My question is why does one event listener operate perfectly fine when added and removed within a function, whereas the other struggles to be added or removed via a function.

Below are the snippets for the four functions:

function addEventListener(){
    canvas.addEventListener("click", funcName ,false);
}
function removecanvasListener(){
    canvas.removeEventListener("click", funcName,false);
}
function addUnitEventListener(){
    canvas.addEventListener("click", difFuncName,false);
}
function removeUnitEventListener(){
    canvas.removeEventListener("click", difFuncName,false);
}

In listenerFile.js:

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");
var x1;

function funcName(event){
    x1 = event.pageX;
    console.log("doing something on click");
}
function difFuncName(event){ 
    console.log("doing something else on click");
}

function addEventListener(){
    canvas.addEventListener("click", funcName ,false);
}
function removecanvasListener(){
    canvas.removeEventListener("click", funcName,false);
}
function addUnitEventListener(){
    canvas.addEventListener("click", difFuncName,false);
}
function removeUnitEventListener(){
    canvas.removeEventListener("click", difFuncName,false);
}

In changingEventListener.js:

function newListenerNeeded(){
    removecanvasListener();
    addUnitEventListener();
}

In ranafterListenerFile.js:

addEventListener(); 

ranafterListenerFile.js is actually loaded after listenerFile.js.

Answer №1

The issue is arising because you assigned the name "addEventListener" to the initial function responsible for adding event listeners. This clashes with a similarly named built-in function.

To resolve this, consider renaming it to something distinct like addMyListener.

var canvas = document.getElementById("myCanvas");
var context = canvas.getContext("2d");

context.fillStyle = "blue";
context.fillRect(0, 0, canvas.width, canvas.height);

var x1;

function funcName(event) {
  x1 = event.pageX;
  console.log("doing something on click");
}

function difFuncName(event) {
  console.log("doing something else on click");
}

function addMyListener() {
  canvas.addEventListener("click", funcName, false);
}

function removecanvasListener() {
  canvas.removeEventListener("click", funcName, false);
}

function addUnitEventListener() {
  canvas.addEventListener("click", difFuncName, false);
}

function removeUnitEventListener() {
  canvas.removeEventListener("click", difFuncName, false);
}

function newListenerNeeded() {
  removecanvasListener();
  addUnitEventListener();
}
addMyListener();
newListenerNeeded();
<canvas id="myCanvas"></canvas>

Answer №2

After reviewing the feedback in the comments section of my inquiry, I have identified the root cause of my issue. It appears that all of my JavaScript code is being invoked within the HTML document at the bottom. Consequently, since they are all loaded together, they are interpreted as a single large file. The problem arises when I attempted to reset the canvas element and listener later on while trying to generate a new canvas object.

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 name of this JavaScript function declaration syntax? (var) => {}

While perusing the most recent NodeJS documentation, I stumbled upon a novel approach to defining a function: fs.unlink('/tmp/hello', (err) => { if (err) throw err; console.log('successfully deleted /tmp/hello'); }); Source: ht ...

Navigating through a React application with several workspaces - the ultimate guide

Currently, I am working on implementing a monorepo setup inspired by this reference: https://github.com/GeekyAnts/nativebase-templates/tree/master/solito-universal-app-template-nativebase-typescript In this repository, there are 4 distinct locations wher ...

PHP AJAX Request Failing to Transfer Files

I am having trouble with sending files in a PHP AJAX Request: Here is the form code: <form class="frmContact" action="#" method="post"> <div class="col-md-6"> <input type="hidden" name="emailTo" id= ...

How to implement a self-invoking function in React JS like you would in regular JavaScript?

Is it possible to invoke the function good without triggering it from an event? I want it to run as soon as the page loads, similar to a self-invoking JavaScript function. Check out this example import React from 'react'; class App extends Reac ...

`sendNodejs header not being transmitted during connection``

My nodejs application utilizes stomp to connect to a server using websockets. However, I am encountering an issue where the application is failing to send the headers that I have specified. Despite referring to clear documentation and examples on how to in ...

Issue with Gulp and Browserify task: Why is there no output?

I've set up the following task in my gulpfile.js gulp.task('default', ['browserify']) gulp.task('browserify', function () { return browserify('./public/js/x.js') .bundle() .pipe(source('y.js& ...

What steps should I take to see my JavaScript code in a web browser?

As a beginner in JS, I'm curious about how to display the results of my code. When I try to use this small snippet of test code, the browser shows a blank page: if ( 11 > 10 ) { console.log("You made it!") } else { console.log("You have ...

Creating a JSON file that contains a collection of discord.js statuses and then seamlessly integrating it into the primary JavaScript document

const userActivities = [ { name: "Morning Jog", type: ActivityType.Running }, { name: "Afternoon Nap", type: ActivityType.Sleeping }, { name: "Evening Game Night", type: ActivityType.Gaming }, { name: "Late Night Code ...

Tips for setting up a proxy with an enum

I am facing an issue with setting up a Proxy for an enum. Specifically, I have an enum where I want to assign a value to this.status using a Proxy. However, despite my expectations, the output "I have been set" does not appear in the console. Can anyone ex ...

What could be the reason why a specific item is not being retrieved by its ID?

Whenever I navigate to the route: '/gallery', all the items from the file './posts.json' are fetched and displayed on the screen. However, upon navigating to the route: '/gallery/:id', my intention is to retrieve a single item ...

Creating a customizable range input for pixel values: a step-by-step guide

I am looking to design a pixel range input. Here is an example: let slider = document.querySelector("input"); slider.addEventListener("change", () => { console.log(slider.value); }); <input type="range" min="5px" max="50px"> However, the r ...

What is the best way to retrieve the latest files from a Heroku application?

Having recently migrated my Discord Bot to Heroku, I faced a challenge with retrieving an updated file essential for code updates. I attempted using both the Git clone command and the Heroku slugs:download command with no success in obtaining the necessar ...

Is it possible to adjust the CSS code linked to the HTML tag based on the specific webpage being viewed?

I am facing an issue with the homepage of my website, which uses Scrollmagic.js for smooth scrolling. In order for the sticky footer CSS to work properly on all other pages, the HTML tag needs to have a height of 100%. However, if I add this height value t ...

Using jquery to transition an image to fade out and then reappear in a different position

There is an image in a div with the highest z-index. Upon clicking on something, the image should fade out and then fade in at a specified position below another image with the class "aaa". The current approach involves using jQuery to fade out the image ...

Include the button beneath the Rating section using JQuery or AJAX

I am having trouble adding buttons after the result.date in my code. Placing the buttons between td tags is causing an [object Object] error to show up. $.ajax({ type: 'GET', url: 'someUrl.php', data: {op : "demo"}, da ...

Formatting ternary expressions in VueJS

VueJS is being utilized by me and it contains an expression as shown below: {{ item.recommendation ? "PS4" : "Xbox" }} Is there a way to make "PS4" appear in red color and "Xbox" in blue color within the expression by incorporating CSS ...

The useStyles function does not automatically update properties in response to changes in variables

I have encountered an issue where the style of a component is not changing based on a boolean state change until I refresh the page. Here's what I'm doing: Within my parent App component, I have the following code: import React from "react"; imp ...

Record every function within the array prototype

Exploring methods that can be accessed on an array object: > console.log(Array.prototype) [] undefined > console.log(Array.prototype.push) [Function: push] Is there a way to view or log all properties/methods accessible on an object's prototyp ...

Is it possible for two node scripts running on the same machine to interfere with each other's execution

In the scenario where a parent node file (such as an express server) spawns child nodes that execute computationally intense tasks, will these children cause blocking for the parent process? ...

What is the best way to create a TypeScript interface or type definition for my constant variable?

I'm facing challenges in defining an interface or type for my dataset, and encountering some errors. Here is the incorrect interfaces and code that I'm using: interface IVehicle { [key: number]: { model: string, year: number }; } interface IV ...