Jeremy Brown Jeremy Brown - 4 years ago 255
Javascript Question

Jquery - How to detect change in browser height without having to refresh the browser?

Code I'm using

var height = $(window).height();

if (height>=768) {
//change class for example.
}
else {
//change class back.
}


The code above works great to detect the view port height and applies the class change as it should, but if I resize the browser window I'd also like this script to detect when that happens and basically re-run the function with the updated height value. How?

I've tried the following solutions which I found on StackOverflow. I was able to successfully implement them, however, I still had to refresh the site in order for the function to apply the class change. It was not doing it on browser resize.

This is one:

var width = $(window).width();

$(window).resize(function(){
if($(this).width() != width){
width = $(this).width();
console.log(width);
}
});


This is the other solution I tried still same issue. I have to refresh the browser in the new view port setting to get it to recognize the difference.

var height = $(window).height();

window.addEventListener('resize', setWindowSize);

function setWindowSize() {
if($(this).height() != height){
height = $(this).height();
console.log(height);
}
}

if (height <= 859 ) {
$(".stats-events-2").removeClass("show-set").addClass("hide-set");
}
else {
$(".stats-events-2").removeClass("hide-set").addClass("show-set");
}


So what I"m trying to do is detect each change in the view port, set that in the script each time it changes so if the view height falls below a certain point a certain class is assigned and vice versa. Any help is much appreciated.

Answer Source
var height = $(window).height();

window.addEventListener('resize', setWindowSize);

function setWindowSize() {
    if($(this).height() != height){
        height = $(this).height();
        console.log(height);
    }
}

if (height <= 859  ) {
    $(".stats-events-2").removeClass("show-set").addClass("hide-set");
} else {
    $(".stats-events-2").removeClass("hide-set").addClass("show-set");
}

As I mentioned in the comments what your trying to do could possibly be accomplished with media queries, if all your after is some styling changes. Aside from that the logic above is only doing the setting of the height on window change. The class change logic is not in the handler, so it's not being evaluated. It would need to be in your handler.

var $window = $(window);
var $statsEvents2 = $(".stats-events-2");

$window.on('resize', function() {
    if ($window.height() <= 859) {
        $statsEvents2.removeClass("show-set").addClass("hide-set");
    } else {
        $statsEvents2.removeClass("hide-set").addClass("show-set");
    }
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download