mouseover not working for dynamic generated li in ie7

1k Views Asked by At

I have created a menuItems array and assigned it to a div which has an id of “leftMenu”.

I have a dynamically generated the UL (user list) and LI and it's append to the div.

I have set two attributes “onmouseover”, and “onmouseout” in the dynamically generated LI.

These two attribute do not work in IE7 but IE8, IE9, Firefox, Safari and Chrome it works fine.

CSS:



    ul{margin:0px; padding:0px; width:200px;}
    li{list-style-type:none;}

    .defaultsMenuBtn {
    background-color: #FEE6A0;
    border-bottom: 1px solid #FFFFFF;
    color: #002C84;
    font-weight: bold;
    padding: 3px 5px;
    }

    a{text-decoration:none;}

    .defaultsMenuBtn_hover{background-color: #FFD14F; padding: 3px 5px; border-bottom: 1px solid #FFFFFF;font-weight:bold; color: #002C84; cursor:pointer;}

HTML



    <div id="leftMenu">  </div>

Javascript



    var menuItems=new Array();
    menuItems[0]="menu01";
    menuItems[1]="menu02";
    menuItems[2]="menu03";
    menuItems[3]="menu04"; 

    var menulength = menuItems.length;
    var MenuWapper = document.getElementById("leftMenu");
    var ul = document.createElement("ul");

    MenuWapper.appendChild(ul);

    for(i=0; i<menulength; i++){
    var li = document.createElement("li");
    var itemID = "item_"+i
    li.className = "defaultsMenuBtn";
    li.id = itemID
    var browser = navigator.appName;

    li.setAttribute("onmouseover","this.className='defaultsMenuBtn_hover'");
    li.setAttribute("onmouseout", "this.className='defaultsMenuBtn'");
    li.innerHTML = " "+menuItems[i]+"";
    ul.appendChild(li);

    }// end forloop

Please let me know if any more information is required!

3

There are 3 best solutions below

3
On

I’m not 100% sure why it doesn’t work in IE7, but I don’t think .setAttribute('event','fn') is supported in IE7-. You should probably replace:

li.setAttribute("onmouseover","this.className='defaultsMenuBtn_hover'");
li.setAttribute("onmouseout", "this.className='defaultsMenuBtn'");

With

li.onmouseover = function() {
    li.className='defaultsMenuBtn_hover';
}

li.onmouseout = function() {
    li.className='defaultsMenuBtn';
}

Setting inline attributes is not a good way to add listeners anyway, it’s better done in javascript.

0
On

This is because in IE7 DOM has restrictions for dynamically added elements.

You have to use the live() or delegate() method with jQuery.

0
On

Thanks David

Here I have made litter change in code

li.className='defaultsMenuBtn_hover';
li.className='defaultsMenuBtn

to

this.className='defaultsMenuBtn_hover';
this.className='defaultsMenuBtn

Now it’s working fine.