Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript variable is undefined, tho it is. why?

Why do I get this (TypeError: $h is undefined) error?

    <div style="clear: both;">
        <input type="button" value="test1" onclick="test1();" />
    </div>
    <div id="box"></div>
    <div id="debug"></div>

        var $h; // also tried without "var"
        $h = $("<div/>").css("position:absolute;top:100px;width:1px;height:1px;background:red;");
        function test1() {
            var start = new Date().getTime();

            for (var i = 0; i < 10000; i++) {
                $h.css("top", (i + 4));
                $h.appendTo("#box");
            }
            var end = new Date().getTime();
            $("#debug").html(end - start);
        }
like image 643
yossi Avatar asked Apr 17 '26 06:04

yossi


1 Answers

The css function called with a string as argument returns the value of the style property having this name.

Of course no style property is named "position:absolute;top:100px;width:1px;height:1px;background:red;", that's why it returns undefined.

What you might want is

 var $h = $("<div/>").css({
    position:"absolute",
    top:"100px",
    width:"1px",
    height:"1px",
    background:"red"
});
like image 179
Denys Séguret Avatar answered Apr 18 '26 18:04

Denys Séguret