javascript - Call a JS function at a set window width - Stack Overflow

I want to call a JavaScript function that checks the width of the window every time it loads and also e

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);
    }
}

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);
    }
}
Share Improve this question asked Aug 10, 2015 at 15:02 SmithySmithy 79110 silver badges30 bronze badges 3
  • Do you want a pure JavaScript answer or one that uses jQuery? – BCDeWitt Commented Aug 10, 2015 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 Commented Aug 10, 2015 at 15:56
  • That's an interesting problem. Can I ask which browser you are having a difficult time with? Also, does this work for you on that browser? It should count up 1 each time yourFunction is called – BCDeWitt Commented Aug 10, 2015 at 18:46
Add a ment  | 

5 Answers 5

Reset to default 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

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.

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.

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.

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>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744867965a4598087.html

相关推荐

  • javascript - Call a JS function at a set window width - Stack Overflow

    I want to call a JavaScript function that checks the width of the window every time it loads and also e

    1天前
    50

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信