skg123
skg123

Reputation: 1

HTML element not resizing when I set window.onresize

I recently started learning about web development, in particular Javascript, and I'm trying to write some simple functions to advance my grasp of the language. I wrote a function to resize a box's height to be proportional to the window, but for some reason it isn't working - the resize function is not updating the page each time I resize the browser window. I feel like I'm making some really silly error, but because I'm not familiar with Javascript I can't figure out what it is.

My HTML is extremely simple:

<body>
<div id = "box">Hi.</div>
</body>

and the Javascript code is:

function resizeToScreen(element, percent)
{
    var wHeight = window.innerHeight;
    var objHeight = wHeight * (percent/100);
    element.style.height = objHeight +"px";
}

window.onresize = resizeToScreen(document.getElementById('box'), 50);

Here's the link to the jsFiddle, which highlights the box yellow: http://jsfiddle.net/sallyg/mb8hB/1/

Upvotes: 0

Views: 1432

Answers (2)

Ian
Ian

Reputation: 50933

You seem to be immediately executing the resizeToScreen function. You need to provide a function reference to onresize, so that it can be called later when the window is resized. Like:

window.onresize = function () {
    resizeToScreen(document.getElementById("box"), 50);
};

You want to bind the event after the DOM is ready, like putting it inside of:

window.onload = function () {
    // HERE
};

should be fine for now, so that resizing doesn't occur before the #box element is ready.

Note that instead of setting .onEVENT properties is fine, but can be overwritten, so it's somewhat suggested to use addEventListener (and attachEvent for old IE).

Here's an example of that, which can hopefully seamlessly be used in both types of browsers:

function addEvent(element, eventName, callback) {
    if (element.addEventListener) {
        element.addEventListener(eventName, callback, false);
    } else if (element.attachEvent) {
        element.attachEvent("on" + eventName, callback);
    }
}

and use it like:

addEvent(window, "load", function () {
    addEvent(window, "resize", function () {
        resizeToScreen(document.getElementById("box"), 50);
    });
});

References:

Upvotes: 3

Tushar Roy
Tushar Roy

Reputation: 362

The problem is in the below statement. You are "calling" resizeToScreen(), and "assigning" its return value to "onresize".

window.onresize = resizeToScreen(document.getElementById("box"), 50);

Instead, you want to "attach" your function to the resize event. This is how you do it:

window.onresize = function () {
    resizeToScreen(document.getElementById("box"), 50);
};.

Upvotes: 0

Related Questions