I am using this script from snipplr, How would I set it so the container div is 100px less than the newWindowHeight height, like -100 or something.
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
//If the User resizes the window, adjust the #container height
$(window).bind("resize", resizeWindow);
function resizeWindow( e ) {
var newWindowHeight = $(window).height();
$("#container").css("max-height", newWindowHeight );
}
});
</script>
$(window). on('resize', function(){ var win = $(this); //this = window if (win. height() >= 820) { /* ... */ } if (win.
jQuery resize() MethodThe resize event occurs when the browser window changes size. The resize() method triggers the resize event, or attaches a function to run when a resize event occurs.
You can use . resize() to get every time the width/height actually changes, like this: $(window). resize(function() { //resize just happened, pixels changed });
Answer: Use the addEventListener() Method You can simply use the addEventListener() method to register an event handler to listen for the browser window resize event, such as window. addEventListener('resize', ...) . The following example will display the current width and height of the browser window on resize.
The script you found over-complicated the issue. The following worked for me:
$(function(){
// Cache reference to our container
var $container = $("#container");
// A function for updating max-height
function updateMaxHeight () {
$container.css("max-height", $(this).height() - 100);
}
// Call updateMaxHeight when browser resize event fires
$(window).on("resize", updateMaxHeight);
});
One warning is that the resize event gets called a lot when resizing the browser; it's not just called after the browser has been resized. As a result, you could have the callback function being called hundreds of times - this is generally a bad idea.
The solution would be to throttle, or debounce the event. Throttling means you won't let the callback be fired more than x times in a span of time (maybe 5 times a second). Debouncing means you fire the callback after a certain span of time has passed from the last resize event (wait until 500 milliseconds after a resize event).
jQuery doesn't presently support a throttle or debounce option, though there are plugins. Other popular libraries you may have used do have these features, such as underscore:
$(function(){
// Cache reference to our container
var $container = $("#container");
// A function for updating max-height
function updateMaxHeight () {
$container.css("max-height", $(this).height() - 100);
}
// Version of updateMaxHeight that will run no more than once every 200ms
var updateMaxHeightThrottled = _.throttle(updateMaxHeight, 200);
// Call updateMaxHeightThrottled when browser resize event fires
$(window).on("resize", updateMaxHeightThrottled);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With