Search code examples
javascriptdom-eventsaddeventlistenerevent-listenerremoveeventlistener

How to stop working of a function with EventListner initiated by HTML attribute 'onclick' on a grid when Clicks on any cell of Grid created using div


I am doing Etch a sketch project with JavaScript and DOM methods. This is what I did👇

  1. created a grid.
  2. ChangeColour() function called using onclick attribute.( Function includes EventListener( Event: mouseover) to give background colour for each cells.)

I want to stop Coloring cells when clicks on any Cell.

I tried return; and removeEventListner() function. Both didn't work.

HTML:

<section id="container"></section>

Javascript:

<script>
let i = 0;
container.innerHTML =
                    `<section class="row">${'<div class="cell" onclick="changeColour()"></div>'.repeat(n)}</section>`
                         .repeat(n)

function changeColour(){

               const cells = document.querySelectorAll('div');
cells.forEach((div) => {
                    div.addEventListener('mouseover', () => {
                         div.setAttribute('style', 'background: black;');
                    })
               })
}
</script>

Solution

  • You can't remove the event handler created from the onclick attribute because you don't have a reference to it - it was created by the HTML parser.

    If you add the event listener in JavaScript instead of HTML, using changeColor as the handler, you should be able to remove it easily. I'm not sure this is exactly what you want to achieve, but along the lines of:

    "use strict";
    const n=3; // testing
    
    container.innerHTML =
        `<section class="row">${'<div class="cell"></div>'.repeat(n)}</section>`
        .repeat(n)
    
    const changeColor = event => {event.currentTarget.style.background="black"}
    const clickHandler = event => {
      document.querySelectorAll('.cell').forEach( cell=> {
        cell.removeEventListener( "click", clickHandler);
        cell.removeEventListener("mouseover", changeColor);
      });
    }
    
    
    document.querySelectorAll('.cell').forEach(div=> {
         div.addEventListener("click",clickHandler);
         div.addEventListener("mouseover", changeColor);
    });
    .cell {
      display: inline-block;
      border: thin solid blue;
      width: 2rem;
      height: 2rem;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" crossorigin></script>
    
    <!-- body-html -->
    <section id="container"></section>