What is the best way to eliminate an event listener from a DOM element?

Looking for help with toggling add/remove event listeners on click. Can anyone provide suggestions to improve my code?

I've searched through various solutions on Stackoverflow without success.

This educational tool involves rotating the center cube to match the displayed number when hovering over the numbers.

Upon page load, an event listener is added to the center cube and additional jQuery code is used to add listeners to any clicked cube to display the hovered number.

The functionality works smoothly in Chrome, somewhat in Opera, but encounters issues in FF and IE.

View current functionality

Event listener added on page load

var thisCube = '.two';
var init = function() {
  var box = document.querySelector(thisCube).children[0],
      showPanelButtons = document.querySelectorAll('#hover-change li'),
      panelClassName = 'show-front',

      hover = function( event ){
        box.removeClassName( panelClassName );
        panelClassName = event.target.className;
        box.addClassName( panelClassName );
      };

  for (var i=0, len = showPanelButtons.length; i < len; i++) {
    showPanelButtons[i].addEventListener( 'mouseover', hover, false);
  }

};

window.addEventListener( 'DOMContentLoaded', init, false);

jQuery code to add a new listener

$('.one, .three, .four, .five, .six, .seven, .eight, .nine').click(function() { 
    thisCube = $(this).data('id');
    init();
});

I suspect that I'm not properly adding the event listeners, leading to issues when comparing with other solutions.

I didn't create a jsfiddle for this post due to the size limitations. Feel free to request it if needed.

Demo built based on this

--EDIT--

Attempted to use the following code to add a class rotate, but encountered difficulties removing the event listener.

$('.one, .two, .three, .four, .five, .six, .seven, .eight, .nine').on('click', function() {

    if($(this).hasClass('rotate'))
    {
        $(this).removeClass('rotate');
        alert('remove ' + $(this).attr("class"));
        $(this).off('click');
    } else {
        $(this).addClass('rotate');
        alert('add ' + $(this).attr("class")); 
        thisCube = $(this).data('id');
        init();
    }
});

-- My Solution --

$('.container').click(function(){
    $(this).toggleClass('rotate');
});

$('#hover-change').children().hover(function(){
    $('.rotate > #cube').removeClass();
    $('.rotate > #cube').addClass($(this).attr('class'));
},
function(){});

Answer №1

If you're looking to incorporate event listeners in your code, consider using jQuery.on for adding them and jQuery.off for their removal.

// Adding Event Listeners
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').on('click', function() { 
    thisCube = $(this).data('id');
    init();
});

// Removing Event Listeners
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').off('click');

For more control, you can utilize Event Namespace:

// Adding Event Listeners with Namespace
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').on('click.MyNamespace', function() { 
    thisCube = $(this).data('id');
    init();
});

// Removing Event Listeners based on Namespace
$('.one, .three, .four, .five, .six, .seven, .eight, .nine').off('click.MyNamespace');

By utilizing Event Namespace, it helps keep your handlers organized without interfering with others.

Hopefully, these suggestions prove helpful in your coding endeavors.

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

Datatables stands out by emphasizing rows across all paginated pages

Encountering an issue with the Datatables plugin when attempting to highlight rows on paginated pages beyond the first one. In the JavaScript code below, you can see where I have commented out adding the class info to all rows. When this is done and you n ...

Generating a new JSON object by extracting URL addresses from an existing JSON and parsing them using JavaScript

I possess a json data file. [ { "line": 1, "elements": [ { "start_timestamp": "2022-10-17T20:07:41.706Z", "steps": [ { "result": { "d ...

Sending data from JavaScript to PHP in the same function

Currently, I am encountering an issue related to passing JavaScript variables to PHP within the same function. Here is a snippet of my code: else if(msg_type[i] == 'code' ){ var code_action = 'test'; <?php function foob ...

The compatibility between Polymer JS and Rails Turbolinks is problematic

Currently, I am facing a challenge in integrating PolymerJs with a Ruby on Rails project that has Turbolinks enabled. The issue arises when I click on a link - the new page loads correctly but my Polymer components do not reinitialize. They appear as if no ...

Is it possible that the Facebook like button is not functioning properly due to being initialized with jQuery?

I'm currently in the process of implementing the Facebook SDK on my website by following this step-by-step guide. After checking the console, I am pleased to report that there are no errors present. $(document).ready(function(){ $.ajaxSetup({ cache ...

Utilizing PHP to send arrays through AJAX and JSON

-I am facing a challenge with an array in my PHP file that contains nested arrays. I am trying to pass an integer variable (and may have to handle something different later on). -My objective is to make the PHP file return an array based on the incoming v ...

Unable to move an element with Webdriver in Java Script

Trying to Drag an Element with the Following Code - "WebElement baseElement = driver.findElement(By.xpath("Element ID"); Actions clicker = new Actions(driver); clicker.moveToElement(baseElement).moveByOffset(20,0).click().perform(); Encount ...

Enhance your JSON formatting with dynamic fields

I am currently working on creating a form with dynamic fields in order to generate a JSON format for posting. The challenge lies in the structure of the JSON, particularly with the "envname" and "value" fields which need to be dynamically added based on us ...

Discover the process of retrieving HTML elements from a different webpage and incorporating them into your own site

As a newcomer, I'm in search of a code that can help me fetch an HTML string from one webpage and use it in another webpage. To illustrate my point, consider the following mock examples. Example 1: Mysite.com/A.html <body> <!---My Script Goe ...

Error message: "Uncaught TypeError in NextJS caused by issues with UseStates and Array

For quite some time now, I've been facing an issue while attempting to map an array in my NextJS project. The particular error that keeps popping up is: ⨯ src\app\delivery\cart\page.tsx (30:9) @ map ⨯ TypeError: Cannot read pr ...

Tips for creating a state change function using TypeScript

Imagine the temperature remains constant for 20 minutes, but at the 21st minute, it changes. The state change is determined by a programmable state change function. How can I create a function to calculate the difference in state change? if(data.i ...

Top-rated online SVG What You See Is What You Get editor

Looking for a drawing program for my website where users can create floor plans and insert text into the images. Does anyone know of a good SVG WYSIWYG editor that can do the job? Otherwise, I might have to resort to using a Flash or Java app, which I&apos ...

The Electron forge project from publisher-github is failing to detect the environment variable GITHUB-TOKEN

I've set up my .env file with the correct token, but I encountered an error when trying to publish my package on GitHub. An unhandled rejection has occurred inside Forge: Error: Please set GITHUB_TOKEN in your environment to access these features at n ...

Showing off HTML tags within react-json-tree

I have incorporated the following npm package into my project: https://www.npmjs.com/package/react-json-tree My goal is to showcase a json tree in react, but I am facing a challenge on how to include an HTML tag as a JSON value. Are there any alternative ...

how to utilize xpath to perform preg_match in php

Trying to extract content utilizing XPATH in php can be a bit challenging. <div class='post-body entry-content' id='post-body-37'> <div style="text-align: left;"> <div style="text-align: center;"> Hi </div></ ...

Utilizing `.back()` in EJS with the powerful combination of Express and M

I'm having trouble with implementing the .back() feature in this code snippet: <a onclick=<% this.window.history.back() %> I keep receiving an error stating "history is undefined," even though there is a history in the window object. Does an ...

Tips on leveraging state values within the makeStyles function in Material UI React

I'm in the process of building a Webpage and incorporating Material UI for the Components. Here's the code: import { makeStyles, Typography } from "@material-ui/core"; const useStyles = makeStyles((theme) => ({ container: { ...

Missing ng-required fields not displaying the has-error validation in AngularJS forms

While editing any part of their address, the user should see a red invalid border around each field to indicate that the full form is required. However, for some reason I can't seem to get the 'Address' field to display this border. The set ...

Difficulty encountered when trying to update intricate model using Angular UI modal

My current project involves managing a model containing nested arrays that represent different sections of a floor plan. Each section contains an array of booth objects. To optimize user interaction, I've created a view that displays all the booths on ...

Concentrate on Managing Text Input Fields in Zend Form

I designed a form using Zend Form and want the focus to be on a text area within the form when the page loads. I attempted to use JavaScript for this purpose, but it only briefly shows the focus before removing it again, preventing any typing. I considere ...