user9048585
user9048585

Reputation:

Javascript window resize not firing onload

I'm working off a specific codepen which can be found here https://codepen.io/anon/pen/WXgvjR .. Its not mine.

Everything works perfect with it, except when i open the page on a mobile or change the browser width to be mobile size, its still displaying some items outside the browser window width ways, is there any way to detect a mobile or change in screen size and just display them going down?

The following is the resize code that is found in the codepen if that helps

$(window).resize(function(){
    var margin=40;
    var padding=15;
    var columns=0;
    var cWidth=300;
    var windowWidth = $(window).width();

    var overflow = false;
    while(!overflow){
        columns++;
        var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
        if(WidthTheory > windowWidth)
            overflow = true;            
    }       
    if(columns > 1)
        columns--;

    var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);

    if( GridWidth != $('#grid').width()){
        $('#grid').width(GridWidth);
    }
});

Any help would be greatly appreciated

Upvotes: 3

Views: 692

Answers (1)

Rence
Rence

Reputation: 2950

Resizing using the Maximise, Minimise, or the Chrome DevTools Devices Buttons, etc. does not trigger the resize event properly (it triggers it before actually resizing, so it does not get the right size).

For the mobile page load, put the same code from the window resize function into the document ready function as well (I would recommend making it a function and then call the function in both to reduce duplicate code):

function setDisplayBoardSize()
{
    var margin=40;
    var padding=15;
    var columns=0;
    var cWidth=300;
    var windowWidth = $(window).width();

    var overflow = false;
    while(!overflow){
        columns++;
        var WidthTheory = ((cWidth*columns)+((columns+1)*padding)+margin);
        if(WidthTheory > windowWidth)
            overflow = true;            
    }       
    if(columns > 1)
        columns--;

    var GridWidth = ((cWidth*columns)+((columns+1)*padding)+margin);

    if( GridWidth != $('#grid').width()){
        $('#grid').width(GridWidth);
    }
}


$(window).resize(function()
{   
    setDisplayBoardSize();
});

$(document).ready(function()
{       
    setDisplayBoardSize();
});

For the min-max etc. see this stackoverflow thread:

jQuery resize() using browser maximise button

This answer specifically should help:

$(window).resize(function()
{   
    setTimeout(function() {
        setDisplayBoardSize();
    }, 100);
});

Upvotes: 1

Related Questions