Reputation: 1127
I want to change the div background color to green onmouseover event but I'm not sure why I keep getting this error TypeError: Cannot read property 'style' of undefined
Here's my JS code:
// JavaScript Document
s1= new String()
var myArray = new Array();
var div_id=0;
myArray[0] = "Donald Duck";
myArray[1] = "Winnie Pooh";
myArray[2] = "Komal Waseem";
myArray[3] = "Hockey";
myArray[4] = "Basketball";
myArray[5] = "Shooting";
myArray[6] = "Mickey Mouse";
function test(){
s1 = document.getElementById('filter').value;
var myRegex = new RegExp((s1),"ig");
arraysearch(myRegex);
}
function arraysearch(myRegex){
var flag=0;
for(b=1; b<=div_id; b++)
{
var d = document.getElementById('lc');
var olddiv= document.getElementById("div" + b);
if(olddiv){
d.removeChild(olddiv);}
}
for(i=0; i<myArray.length; i++)
{
if (myArray[i].match(myRegex)){
div_id++;
flag=1;
document.getElementById('lc').style.visibility='visible';
var element = document.createElement("div");
element.setAttribute('id', "div" + div_id);
element.appendChild(document.createTextNode(myArray[i]));
document.getElementById('lc').appendChild(element);
var x =document.getElementsByTagName("div")
for(t=0; t<x.length; t++)
{
//alert(t);
if(x[t]){
x[t].onmouseover = function(){
x[t].style.backgroundColor='green';
}
}
}
}
if (flag ==0){
document.getElementById('lc').style.visibility='hidden'; }
}
}
Upvotes: 1
Views: 5854
Reputation: 178
In case, if you want the div
to be green onhover, e.g: div id is mydiv, you could simply do something like this in your css.
#mydiv{
background-color:red;
}
#mydiv:hover{
background-color:green;
}
Upvotes: 2
Reputation: 251182
You could either change your JavaScript, this should work:
x[t].onmouseover = function() {
this.style.backgroundColor='green';
}
The reason your original JavaScript doesn't work is because t
has changed by the time you mouse-over, so x[t]
inside the event handler cannot work.
Or you could use CSS:
div.myDiv:hover {
background-color: green;
}
Upvotes: 2