blackhill24
blackhill24

Reputation: 452

jQuery responsive function not working until screen size changes

Im using the jQuery below to move some elements about on my page based on the user's screen size.

The problem I have is that the code works fine but only when you manually resize the screen even by only 1px it fires but never when the document loads?

Any ideas where I've gone wrong?

jQuery(document).ready(function () {

    /*
     * windowSize
     * call this function to get windowSize any time
    */

    function windowSize() {
        windowHeight = window.innerHeight ? window.innerHeight : 
        $(window).height();
        windowWidth = window.innerWidth ? window.innerWidth : $(window).width();      
    }

    //Init Function of init it wherever you like...
    windowSize();

    // For example, get window size on window resize
    $(window).resize(function() {
        windowSize();
        //console.log("width is :", windowWidth, "Height is :", windowHeight);
        if (windowWidth > 1029) {
            $("#single-related").appendTo("#product-team-shop");
        } 
    });        
});

Upvotes: 0

Views: 152

Answers (1)

rrobben
rrobben

Reputation: 483

It's because the window resize event only gets triggered when the window is resized.

If you want to execute a function onLoad you can do it like this:

jQuery(document).ready(function () {

  // Function executed once the document is loaded
  windowSize();

  // The function windowSize will execute when the window gets resized
  $(window).resize(function() {
    windowSize();
  });   

  function windowSize() {
    windowHeight = window.innerHeight ? window.innerHeight : $(window).height();
    windowWidth = window.innerWidth ? window.innerWidth : $(window).width();
    // This will make sure it checks the window size once the document is loaded but also whenever a resizeEvent occurs     
    checkWindowWidth();
  }

  function checkWindowWidth() {
    if (windowWidth > 1029) {
        $("#single-related").appendTo("#product-team-shop");
        console.log('resized width greater than 1029');
    }
  }
});

I've put the append and console code in a function named checkWindowWidth. I execute that whenever windowSize function is called and whenever a resize event occurs.

Because the windowSize function is called once the document is loaded this means that the checkWindowWidth function is fired at document load and when the window gets resized.

Upvotes: 1

Related Questions