2

I want to call a JavaScript function that checks the width of the window every time it loads and also every time the screen is re-sized. The reason for this is i dont want a function to be used when the screen size gets too small e.g. mobile size.

Can this be done?

Ive tried doing something like this

window.onload = function () {
    if (window.onload.innerWidth > 991 || window.onresize.innerWidth > 991) {
        var maxHeight = 0;
        setTimeout(function () {
            maxHeight = 0;
            $(".menu> div").each(function () {
                var thisHeight = parseInt($(this).css("height").toString().replace("px", ""));
                if (thisHeight > maxHeight) {
                    maxHeight = thisHeight;
                }
            });
            $(".menu> div").css("height", maxHeight.toString() + "px");
            $(".menu").sortable({
                handle: "h3",
                placeholder: {
                    element: function (currentItem) {
                        return $("<div class='col-md-4 placeholderBlock' style='height:" + (maxHeight).toString() + "px; '></div>")[0];
                    },
                    update: function (container, p) {
                        return;
                    }
                }
            });
            $(".menu").disableSelection();

            $(".widget").each(function () {
                $(this).click(function () {
                    enableDisableWidget($(this));
                });
            });

            setInterval(function () {
                var menu= { items: [] };
                $(".menu> div").each(function () {
                    menu.items.push(
                        {
                            classes: "." + $(this).attr("class").replace(/\ /g, ' ')
                        }
                    );
                });
                $(".hiddenField_dashboardLayout").val(JSON.stringify(dashboardItems));
            }, 500);
        }, 2000);
    }
}
Smithy
  • 689
  • 9
  • 25
  • Do you want a pure JavaScript answer or one that uses jQuery? – BCDeWitt Aug 10 '15 at 15:48
  • @BDawg Either would be fine. Ive tried to use some of the suggestions below but they only seem to work once. E.g if i resize the page more than once the function does not seem to fire – Smithy Aug 10 '15 at 15:56
  • That's an interesting problem. Can I ask which browser you are having a difficult time with? Also, does [this](https://jsfiddle.net/35rnzhob/) work for you on that browser? It should count up 1 each time yourFunction is called – BCDeWitt Aug 10 '15 at 18:46

5 Answers5

2

you could have a function check the window.innerWidth is bigger then your limit size

var limitFunc = function(){
    if (window.innerWidth>999){
       /*your functions for big screen*/
     console.log('bigScreen')
    }
};

you fire the limit function on window resize and onload events

window.addEventListener("resize", limitFunc);
window.addEventListener("onload", limitFunc);

fiddle

maioman
  • 15,071
  • 4
  • 30
  • 42
1

window.onload.innerWidth > 991 || window.onresize.innerWidth

That isn't going to work. those are both event properties that do not have a property called innerWidth.

You'll need to change that to:

document.body.offsetWidth, window.innerWidth or document.documentElement.clientWidth

The onload will do what you want on page load.

Add another event called onresize

$(window).on("resize", function(){});

You can also use CSS for this:

@media only screen and (min-width: 991px) { ... }

The css rules between the curly brackets will only be applied when the screen is larger than 991 pixels.

Mouser
  • 12,807
  • 3
  • 25
  • 51
0

You can add a listener to the resize event using jQuery:

$(window).on("resize", function(){
    console.log("resized");
});

Or the pure javascript way, courtesy of this answer.

var addEvent = function(object, type, callback) {
    if (object == null || typeof(object) == 'undefined') return;
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
};

addEvent(window, "resize", function(event) {
  console.log('resized');
});

I wrote this code hoping to fulfill your needs. Pure javascript:

//this function will return true if the window is too small
var isTooSmall = function(w, h){
    console.log(w + " " + h); //just to check width and height
    var min_w = 200; //set these to what you wish
    var min_h = 200;
    if(w < min_w || h < min_h){
        return true;
    }
    else return false;
};

//this function will allow us to bind listeners given an object and its event.
//Check the linked stackoverflow answer for more explanation
var addEvent = function(object, type, callback) {
    if (object == null || typeof(object) == 'undefined') return;
    if (object.addEventListener) {
        object.addEventListener(type, callback, false);
    } else if (object.attachEvent) {
        object.attachEvent("on" + type, callback);
    } else {
        object["on"+type] = callback;
    }
};

//resize listener
addEvent(window, "resize", function(event) {
    console.log(isTooSmall(window.innerWidth, window.innerHeight));

});

//onload listener
window.onload = function () { 
    console.log(isTooSmall(window.innerWidth, window.innerHeight));
}

Here's a jsfiddle to see it in action.

Community
  • 1
  • 1
Tom Solacroup
  • 276
  • 3
  • 16
0

This should work for you:

function yourFunction() {
    if (window.innerWidth >= 992) {
        //TODO: Your code here
    }
}

// Set both event handlers to same function
window.onload = window.onresize = yourFunction;

By the way, the line...

if (window.onload.innerWidth > 991 || window.onresize.innerWidth > 991)

...doesn't work because window.onload and window.onresize are meant to be functions.

BCDeWitt
  • 4,087
  • 1
  • 16
  • 31
0

function myFunction() {
    var w = window.outerWidth;
    //var h = window.outerHeight;
    
    if (w > 991) {
      document.getElementById("p").innerHTML = "big " + w;
    } else {
      document.getElementById("p").innerHTML = "small " + w;
    }
}
<body onresize="myFunction()" onload="myFunction()">
<p id="p"><p>
</body>
antelove
  • 2,039
  • 16
  • 14