Search code examples
javascriptjqueryif-statementonload-eventonresize

What is a good way to make an event occur when the page has loaded OR on each resize?


I need a query to check the viewport width each time the document is ready or whenever the viewport gets resized. The reason is that I want the main navigation to look and behave differently for different viewport widths.

//EventListener to get viewport width on load
window.addEventListener("load", function () {
    window.loaded = true;
});

//get Window Size on Resize
var width = $(window).width();
$(window).on('resize', function reportWindowSize() {
  if ($(this).width() != width) {
    width = $(this).width();
    console.log(width);
  }
});

Then I think I need a query like this:

If (page loaded OR viewport width changes) {
   if (viewport width > x) {
     do things

} else if (viewport width < x) {
     do other things
  }
};

What would be a good way to form If (page loaded OR viewport width changes) into a JavaScript or jQuery expression?


Solution

  • As Terry pointed out in his comment, you can create a function and reuse it in each of the scenarios that you need it.

    I.E.

    function checkWidth() {
      let windowWidth = $(window).width();
      let maxWidth = 1000;
      if(windowWidth < maxWidth) {
        // do your stuff
      }
    }
    
    $(document).ready(function() {
      checkWidth();
    });
    
    $(window).on('resize', function() {
      checkWidth();
    });
    

    Another solution would be to use Media Queries inside JS.

    You can watch for a media query as you would in CSS with the following code:

    if (matchMedia) {
      let mq = window.matchMedia("(min-width: 500px)");
      mq.addListener(checkWidth);
      checkWidth(mq);
    }
    
    // media query change
    function checkWidth(mq) {
      if (mq.matches) {
      // do your stuff
      }
    }
    

    You need to call checkWidth after adding the event listener in order to ensure that it executes when the page is loaded.

    I got this example from: https://www.sitepoint.com/javascript-media-queries/