简体   繁体   中英

Javascript - how to call function correctly

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!

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

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

the DOM object is not completely loaded when you call resizeElementHeight.replace by is:

    $(document).ready(function() {
    resizeElementHeight($('#global_image')[0]);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM