AllisonC
AllisonC

Reputation: 3099

Why is my global variable null?

var matte_canvas_width = $("#matte_canvas").width();
var matte_canvas_height = $("#matte_canvas").height();
function moulding_draw(img, fillet)
{

  //var matte_canvas_width = $("#matte_canvas").width();
  //var matte_canvas_height = $("#matte_canvas").height();
  console.log("matte_canvas_width: " + matte_canvas_width);
  console.log("matte_canvas_height: " + matte_canvas_height);
}

When I declare the variables outside of the function, the console outputs null as the values. Why is this happening?

Upvotes: 0

Views: 738

Answers (3)

Hamed Ali Khan
Hamed Ali Khan

Reputation: 1118

correct way of doing this will be

var matte_canvas_width;
var matte_canvas_height;

$(document).ready(function() {
    matte_canvas_width = $("#matte_canvas").width();
    matte_canvas_height = $("#matte_canvas").height();
    moulding_draw("", "");
});

function moulding_draw(img, fillet)
{

  //var matte_canvas_width = $("#matte_canvas").width();
  //var matte_canvas_height = $("#matte_canvas").height();
  console.log("matte_canvas_width: " + matte_canvas_width);
  console.log("matte_canvas_height: " + matte_canvas_height);
}

Upvotes: 1

Mithun Satheesh
Mithun Satheesh

Reputation: 27855

the lines

var matte_canvas_width = $("#matte_canvas").width();
var matte_canvas_height = $("#matte_canvas").height();

should be called at the time when the dom is properly loaded.

Upvotes: 2

Grant Thomas
Grant Thomas

Reputation: 45083

It could be that it was never anything in the first place, though you think you have set it.

How to you know $("#matte_canvas").width(); is giving you the value initially?

Upvotes: 0

Related Questions