Im trying to write a function that resizes the css widths of some elements when the browser window is resized, right now I dont seem to be getting things right and would love it if someone could help me out on where Im going wrong, my code so far is:
function windowResize() {
$('#content').css('width', $windowWidth);
$('#div.mySection').css('width', $windowWidth);
$('#div.mySection .story').css('width', $windowWidth);
}
$(document).ready(function() {
var $windowWidth = $(window).width();
$(window).resize(function() {
windowResize();
});
});
Im not sure if I have placed everything in its correct place, if someone could advise me on how I can make this code much better it would be great.
Thanks
Kyle
You’ll want to recalculate
window‘s new dimensions inside of the function you’re running when the window resizes; otherwise, you will wind up with the same width being repeated forever. (Incidentally, your$windowWidthvariable is outside of the scope of yourwindowResizefunction, which is why it is not being used now.)By convention, variables storing jQuery objects are prefixed with
$, so I removed that fromwindowWidth, which is a plain old Number.Now, here’s the caveat for your code:
resizefires continuously in certain browsers, which means you are going to be running your handler continuously, too, which could be a very bad thing. Give Ben Alman’s throttle/debounce plugin a try; it will limit the number of times your handler is called, “debouncing” or “throttling” execution to once for a given interval. That way, you’ll achieve your effect without spamming resizes to your DOM elements (which can be painful and is a good way of locking a UI).