yossi
yossi

Reputation: 3164

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);
        }

Upvotes: 3

Views: 78

Answers (1)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

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"
});

Upvotes: 5

Related Questions