[jquery] jQuery on window resize

I have the following JQuery code:

$(document).ready(function () {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
});

The only problem is that this only works when the browser first loads, I want containerHeight to also be checked when they are resizing the window?

Any ideas?

This question is related to jquery html css

The answer is


Here's an example using jQuery, javascript and css to handle resize events.
(css if your best bet if you're just stylizing things on resize (media queries))
http://jsfiddle.net/CoryDanielson/LAF4G/

css

.footer 
{
    /* default styles applied first */
}

@media screen and (min-height: 820px) /* height >= 820 px */
{
    .footer {
        position: absolute;
        bottom: 3px;
        left: 0px;
        /* more styles */
    }
}

javascript

window.onresize = function() {
    if (window.innerHeight >= 820) { /* ... */ }
    if (window.innerWidth <= 1280) {  /* ... */ }
}

jQuery

$(window).on('resize', function(){
    var win = $(this); //this = window
    if (win.height() >= 820) { /* ... */ }
    if (win.width() >= 1280) { /* ... */ }
});

How do I stop my resize code from executing so often!?

This is the first problem you'll notice when binding to resize. The resize code gets called a LOT when the user is resizing the browser manually, and can feel pretty janky.

To limit how often your resize code is called, you can use the debounce or throttle methods from the underscore & lowdash libraries.

  • debounce will only execute your resize code X number of milliseconds after the LAST resize event. This is ideal when you only want to call your resize code once, after the user is done resizing the browser. It's good for updating graphs, charts and layouts that may be expensive to update every single resize event.
  • throttle will only execute your resize code every X number of milliseconds. It "throttles" how often the code is called. This isn't used as often with resize events, but it's worth being aware of.

If you don't have underscore or lowdash, you can implement a similar solution yourself: JavaScript/JQuery: $(window).resize how to fire AFTER the resize is completed?


Give your anonymous function a name, then:

$(window).on("resize", doResize);

http://api.jquery.com/category/events/


Use this:

window.onresize = function(event) {
    ...
}

You can bind resize using .resize() and run your code when the browser is resized. You need to also add an else condition to your if statement so that your css values toggle the old and the new, rather than just setting the new.


jQuery has a resize event handler which you can attach to the window, .resize(). So, if you put $(window).resize(function(){/* YOUR CODE HERE */}) then your code will be run every time the window is resized.

So, what you want is to run the code after the first page load and whenever the window is resized. Therefore you should pull the code into its own function and run that function in both instances.

// This function positions the footer based on window size
function positionFooter(){
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    else {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    } 
}

$(document).ready(function () {
    positionFooter();//run when page first loads
});

$(window).resize(function () {
    positionFooter();//run on every window resize
});

See: Cross-browser window resize event - JavaScript / jQuery


function myResizeFunction() {
  ...
}

$(function() {
  $(window).resize(myResizeFunction).trigger('resize');
});

This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.

UPDATE: Here's another option if you don't want to make use of any other third-party libraries.

This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).

It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.

function myResizeFunction() {
  var $window = $(this),
      height = Math.ceil($window.height()),
      previousHeight = $window.data('previousHeight');

  if (height !== previousHeight) {
    if (height < 819)
      previousHeight >= 819 && $('.footer').removeClass('hgte819');
    else if (!previousHeight || previousHeight < 819)
      $('.footer').addClass('hgte819');

    $window.data('previousHeight', height);
  }
}

$(function() {
  $(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});

As an example, you might have the following as some of your CSS rules:

.footer {
  bottom: auto;
  left: auto;
  position: static;
}

.footer.hgte819 {
  bottom: 3px;
  left: 0;
  position: absolute;
}

Try this solution. Only fires once the page loads and then during window resize at predefined resizeDelay.

$(document).ready(function()
{   
   var resizeDelay = 200;
   var doResize = true;
   var resizer = function () {
      if (doResize) {

        //your code that needs to be executed goes here

        doResize = false;
      }
    };
    var resizerInterval = setInterval(resizer, resizeDelay);
    resizer();

    $(window).resize(function() {
      doResize = true;
    });
});

Move your javascript into a function and then bind that function to window resize.

$(document).ready(function () {
    updateContainer();
    $(window).resize(function() {
        updateContainer();
    });
});
function updateContainer() {
    var $containerHeight = $(window).height();
    if ($containerHeight <= 818) {
        $('.footer').css({
            position: 'static',
            bottom: 'auto',
            left: 'auto'
        });
    }
    if ($containerHeight > 819) {
        $('.footer').css({
            position: 'absolute',
            bottom: '3px',
            left: '0px'
        });
    }
}

can use it too

        function getWindowSize()
            {
                var fontSize = parseInt($("body").css("fontSize"), 10);
                var h = ($(window).height() / fontSize).toFixed(4);
                var w = ($(window).width() / fontSize).toFixed(4);              
                var size = {
                      "height": h
                     ,"width": w
                };
                return size;
            }
        function startResizeObserver()
            {
                //---------------------
                var colFunc = {
                     "f10" : function(){ alert(10); }
                    ,"f50" : function(){ alert(50); }
                    ,"f100" : function(){ alert(100); }
                    ,"f500" : function(){ alert(500); }
                    ,"f1000" : function(){ alert(1000);}
                };
                //---------------------
                $(window).resize(function() {
                    var sz = getWindowSize();
                    if(sz.width > 10){colFunc['f10']();}
                    if(sz.width > 50){colFunc['f50']();}
                    if(sz.width > 100){colFunc['f100']();}
                    if(sz.width > 500){colFunc['f500']();}
                    if(sz.width > 1000){colFunc['f1000']();}
                });
            }
        $(document).ready(function() 
            {
                startResizeObserver();
            });

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width