Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery function on window events (load and resize)

I'm not sure how to use the order of the window events load and resize on jQuery to make it work when resizing. The first function is used to get the total width except the scrollbar width, because the CSS is using the device width, but the JS is using the document width.

The second function adds a style when the total screen width is between 768px and 1024px, and it should work when I load the page at any screen, after resizing, etc. I'm doing a lot of tests and I think the problem is about the window events order.

For being more specific about the problems, it doesn't remove the style when I load the page at 900px and I expand it to > 1024px! Or by the contrary, it doesn't add the style when I load the page at 1300px and I shorten the width to 900px.

I think it's 'cause of the load and resize events order, but I'm not totally sure. Or maybe I'm not doing the correct declaration of the variable into the resize.

The code:

function viewport() {
    var e = window, a = 'inner';
    if (!('innerWidth' in window )) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return { width : e[ a+'Width' ] , height : e[ a+'Height' ] };

}

$(document).ready(function(){        
    var vpwidth=$(window).width();    

        $(window).on('resize', function(){            
            var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;

                if(vpwidth >= 768 && vpwidth <= 1024) {
                    $('.contentleft, .contentright').css('width', changeWidth + 'px');
                } else {
                    $('.contentleft, .contentright').removeAttr('style');
                }

        }).resize();

});
like image 589
Unix Avatar asked Feb 16 '26 10:02

Unix


1 Answers

I believe the issue is that you're not re-calculating the vpwidth on resize, So the value you got when the page was loaded will be used every time window is resized.

try

$(document).ready(function(){            

    $(window).on('resize', function(){ 
       var vpwidth=$(window).width(); // get the new value after resize
       var changeWidth = (($('.main-content .wrap').width() * 96.3)/100) - 312;

       if(vpwidth >= 768 && vpwidth <= 1024) {
           $('.contentleft, .contentright').css('width', changeWidth + 'px');
        } else {
            $('.contentleft, .contentright').removeAttr('style');
        }

    }).resize();

});
like image 159
T J Avatar answered Feb 18 '26 22:02

T J



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!