Home > Mobile >  Object not defined when eventlistener i triggered
Object not defined when eventlistener i triggered

Time:09-28

<!DOCTYPE html>
<html>
<head>
<style>
span {
  font-family:Verdana, Arial, sans-serif;
  font-size:14px;
}  
span:hover {
  display: fit-content;
  background-color: lightgrey;
  cursor:pointer;
}
</style>
</head>
<body>
<span>3.1415</span>
</body>
<script>
  function setBckCol(col) {
    this.style.backgroundColor = col;
  }
  function setSpanListeners() {
    var spans = document.querySelectorAll('span');
    for(var i = 0; i < spans.length ;i  ) {
      spans[i].addEventListener('click', setBckCol('#F9E79F'));                    
    }
 }
const nodeList = document.querySelectorAll("span");
for (i = 0; i < nodeList.length; i  ) {
  nodeList[i].style.backgroundColor = "red";
}
setSpanListeners();
</script>
</html>

I am getting the error message in Chrome developer tools when executing the script. The error refers to line 21, see the attached image.

Snippet from Chrome developer toools

Seems "this" is not passed to the setBckCol function. How to correct it?

CodePudding user response:

you are only passing color to the setbckcol setBckCol('#F9E79F') instead you have to pass the element & the color.setBckCol(spans[i],'#F9E79F').

also have to collect both of them function setBckCol(el,col)

function setBckCol(el,col) {
  el.style.backgroundColor = col;
}

function setSpanListeners() {
  var spans = document.querySelectorAll('span');
  for (var i = 0; i < spans.length; i  ) {
    spans[i].addEventListener('click', setBckCol(spans[i],'#F9E79F'));
  }
}
const nodeList = document.querySelectorAll("span");
for (i = 0; i < nodeList.length; i  ) {
  nodeList[i].style.backgroundColor = "red";
}
setSpanListeners();
span {
  font-family: Verdana, Arial, sans-serif;
  font-size: 14px;
}

span:hover {
  display: fit-content;
  background-color: lightgrey;
  cursor: pointer;
}
<body>
  <span>3.1415</span>
  <span>3.1415</span>
</body>
>

  • Related