JavaScript – invalid argument IE8

internet-explorer-8javascript

I've got a little JavaScript problem. The code is working in Opera and Firefox browser but not in Internet Explorer 8. Does anybody know why?

function createbtn(object, inner) {
    var hover = document.createElement("div");
    hover.setAttribute("class", "myarea");
    if (inner) {
        hover.style.width = object.width - 16 + "px";
        hover.style.height = object.height - 16 + "px";
        hover.style.top = getposy(object) + "px";
        hover.style.left = getposx(object) + "px";
    } else {
        hover.style.width = object.width + "px";
        hover.style.height = object.height + "px";
        hover.style.top = getposy(object) - 8 + "px";
        hover.style.left = getposx(object) - 8 + "px";
    }
}

I'm just learning Javascript. Any feedback welcome.
Simon

Best Answer

If object.width is less than 16

hover.style.width = object.width - 16 + "px";

then this will produce a string with a negative sign at the front, which is illegal since widths have to be non-negative.

You can fix this by saying

hover.style.width = Math.max(object.width - 16, 0) + "px";

and similarly for height.

Many browsers ignore invalid content, but IE in certain modes is stricter, so you are probably just getting silent failure in the others.