Reputation: 1084
I don't really understand how to call a Javascript function properly on document ready. My goal is to resize a div depending on the height of browser window, and I took this code from another answer on SO. What am I doing wrong?
function resizeElementHeight(element) {
var height = 0;
var body = window.document.body;
if (window.innerHeight) {
height = window.innerHeight;
} else if (body.parentElement.clientHeight) {
height = body.parentElement.clientHeight;
} else if (body && body.clientHeight) {
height = body.clientHeight;
}
element.style.height = ((height - element.offsetTop) + "px");
}
$(document).ready(resizeElementHeight($('#global_image')));
The element I am trying to call has the id "global_image", but I get "cannot set property height of undefined", and I feel lost in how to providing the right element to the function. Thanks for your help!
Upvotes: 0
Views: 521
Reputation: 31
the DOM object is not completely loaded when you call resizeElementHeight.replace by is:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});
Upvotes: 0
Reputation: 736
The function resizeElementHeight expects a DOM-element, not a JavaScript object. To expand on techfoobar's answer you should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image')[0]);
});
Upvotes: 1
Reputation: 66693
ready()
expects a function as its argument. Right now, you are calling resizeElementHeight()
and passing its return value to ready()
.
In your current code, at the point of calling resizeElementHeight()
the DOM is not yet ready and the element #global_image
is not yet in the DOM tree.
You should change it to:
$(document).ready(function() {
resizeElementHeight($('#global_image'));
});
Upvotes: 5