Wayne Werner
Wayne Werner

Reputation: 51807

IE New Element with Style?

I have this stylesheet:

.pixel{
    position: absolute;
    height: 10px;
    width: 10px;
    background-color: #ffcc00;
    font-size: 0px;
}

And this javascript:

function drawpixel(x,y){
    el = document.createElement('div');
    el.setAttribute('class','pixel');
    el.style.left = x;
    el.style.top = y;
    /*  IE needs this for some reason?
    el.style.position = "absolute";
    el.style.backgroundColor = "#FFCC00";
    el.style.width = "2px";
    el.style.height = "2px";
    */
    el.style.fontSize = "0px";
    el.style.lineHeight = "0px";
    document.body.appendChild(el);
}

function mover(event){
    element = document.getElementById("coords");
    element.innerHTML = event.clientX + " " + event.clientY;
    drawpixel(event.clientX, event.clientY);
} 

Which allows me to "draw" with divs. But IE requires those 4 commented lines - it won't read the class information for some reason?

Is there any easier way to "fix" it for IE, or do I pretty much just have to have those 4 lines?

thanks

Upvotes: 3

Views: 267

Answers (2)

John Hartsock
John Hartsock

Reputation: 86872

Just use el.className = "pixel";

Just something else I noticed. I know the question states that this is for IE but it looks like you are using your mover(event) in an event handler. If you are using Firefox and other browsers you may want to consider coding the mover function like this:

function mover(evt){  
    evt = evt || event;                                                           
    element = document.getElementById("coords");                                 
    element.innerHTML = evt .clientX + " " + evt .clientY;                     
    drawpixel(evt.clientX, evt.clientY);                                     
} 

Upvotes: 5

scunliffe
scunliffe

Reputation: 63588

In IE (due to this bug) you need to change this:

el.setAttribute('class','pixel');  

to

el.setAttribute('className','pixel');  

IE's implementation of setAttribute() is woefully broken before IE8 (running in IE8 standards mode)

Upvotes: 4

Related Questions