1

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>
Roshith
  • 35
  • 6

1 Answers1

1

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>
traktor
  • 17,588
  • 4
  • 32
  • 53
  • Is there another way? When I do another action(like double click), I want to stop 'mouseover' Event Listener (or) stop the entire function. – Roshith Jul 16 '22 at 07:41
  • Please read the answer completed as intended (I hit the enter key by accident and posted it early). What ever you do you need to retain a reference to event handler functions in order to remove them using `removeEventListener`. Removing them by setting HTML element `oneventname` attributes to null is so HTML 3 that I don't want to even consider going there. – traktor Jul 16 '22 at 08:06