+ 1
Why this code not working?
Why I run this code in my pc I'm getting cannot read property 'style' of undefined. https://code.sololearn.com/W3dtSCGILq6s/?ref=app
3 Answers
+ 3
At running time of the js tab, no element from the page <body> was parsed (the script is inserted at end of the <head>) so the loop iterate over an empty array and initialize none event listeners.
You must wrap your code in a onload event listener to run the code after the page was completly loaded (or insert explicitly the script after the targeted elements).
The temporary variable xi is useless, as it will keep only the reference of the last selected element ^^ However, you can use 'this' context inside the event handler function, and you should define the inverse event handler ('blur') to reset the default (none) background color when another element get the focus:
onload = function() {
var x=document.getElementsByClassName("jkl");
for (var i=0; i<x.length; i++){
x[i].addEventListener("focus",bblue);
x[i].addEventListener("blur",bnone);
}
function bblue(){
this.style.backgroundColor="blue";
}
function bnone(){
this.style.backgroundColor="";
}
};
+ 1
Russ it's not working.thanks for response.
+ 1
visph you are right actually when event occur after function run then value of i is 2 because for loop already executed and there is no element in 2 position.that's why getting undefined error but we can use this instead of i variable.