Home>

Created a script that works with a screen width of 820 pixels. This script switches the color of the second block Block_changewhen clicked, then when the screen is more than 820 pixels, the color of the Block_changeblock returns to its original color (orange) and clicking on the block stops working.

The essence of the problem: When you change the screen to a large, then to a smaller side (820px), clicking on the block works every other time, but according to the idea, the clicker should work fine.

I know I hung the clicker wrong, but I don't know how to fix it.

On this site, the editor does not show the essence of the problem, try it locally on your computer.

let Block_click= document.querySelector(".Block_click");
let Block_change= document.querySelector(".Block_change");
const MediaQuery= window.matchMedia('(max-width: 820px)');
function RemoveClass(e) {
  if (e.matches) {
    Block_click.addEventListener('click', function() { //I hung the event listener incorrectly, how can I fix this?
      Block_change.classList.toggle("change_color");
    })
  } else {
    Block_change.classList.remove("change_color");
  }
}
MediaQuery.addEventListener('change', RemoveClass);
RemoveClass(MediaQuery);
.Block_click {
  user-select: none;
  width: 200px
  background: grey;
  font-size: 22px;
}
.Block_change {
  margin-top: 20px;
  width: 200px
  background: orange;
  font-size: 22px;
}
.change_color {
  background: red;
}
<div class='Block_click'>CLICKER</div><div class='Block_change'>Color change</div>