Search code examples
javascriptonload

javascript onload function works, onresize does not


I have a function in my header to adjust the size of an iframe and I call it in the footer for both window.onload and window.onresize.

var resize = function(elementId) {
        document.getElementById(elementId).height = parseInt(document.getElementById(elementId).offsetWidth)*0.63;
    };

onload works:

window.onload = resize("youtube");

onresize does not:

window.onresize = resize("youtube")

Forgive me if I'm doing anything wrong with my javascript. I'm still kind of new to it.


Solution

  • You are executing the function right away instead of returning a function.

    So if you log what window.onload contains, it would contain undefined

    You need to return a function (also you might want to cache the element, like I did):

    var resize = function(elementId) {
        return function(){
            var element = document.getElementById(elementId);
            element.height = parseInt(element.offsetWidth) * 0.63;
        };
    };
    

    What the above does still allows for you to do:

    window.onload = resize("youtube");
    

    Since resize now returns a callback window.onload (in theory) is now the same as:

    window.onload = function(){
        var element = document.getElementById("youtube");
        element.height = parseInt(element.offsetWidth) * 0.63;
    };