0

I decided to change onclick events to event listener and got a problem. Case a works, and Case b doesn't. Debugger shows that this equals window type, not element

  testName.setAttribute("onclick", "toggleTestsWindow(this)");

  // b
  testName.addEventListener("click", () => toggleTestsWindow(this));
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Colly
  • 1
  • 1
  • 2

1 Answers1

0

This is how I usually write event listeners:

// Identifies the HTML element
const mySpan = document.getElementById("mySpan");

// Calls `changeColor` whenever `mySpan` receives a click event
mySpan.addEventListener("click", changeColor);

// Defines `changeColor`
function changeColor(event){
  // The listener can automatically have access to the triggering event
  //   (We call it 'event' for our own convenience)

  // The event's `target` property gives us the element where
  //   the event occurred
  const targ = event.target;

  // Makes some visible change to the DOM 
  if(targ.classList.contains("blue")){
    targ.classList.remove("blue");
  }
  else{
    targ.classList.add("blue");
  }
}
.blue { background-color: lightSkyBlue; }
<span id="mySpan">CLICK ME</span>
Cat
  • 4,141
  • 2
  • 10
  • 18