Javascript variable is undefined, this is it. What for?

Why am I getting this error ( TypeError: $h is undefined

)?

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

      

+3


source to share


1 answer


A function css

called with a string as an argument returns the value of the style property that has that name.

Of course, the style property is not called "position:absolute;top:100px;width:1px;height:1px;background:red;"

, so it returns undefined

.



What you can wish for is

 var $h = $("<div/>").css({
    position:"absolute",
    top:"100px",
    width:"1px",
    height:"1px",
    background:"red"
});

      

+5


source







All Articles