Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

conditional javascript execution based on browser window size?

I have a simple jQuery function--detailed below-- that I'm using to manipulate the position of the document header, and I'm wondering if I can add a parameter such that the function is only executed if the browser window is of a certain size? In this case, I'd like the "stickyHeaderTop" function to execute only if the browser window width exceeds 1024px; is this possible?

<script type="text/javascript">
    $(function(){
    var stickyHeaderTop = $('header').offset().top;

    $(window).scroll(function(){
            if( $(window).scrollTop() > stickyHeaderTop ) {
                    $('header').css({position: 'fixed', top: '0px'});
            } else {
                    $('header').css({position: 'relative', top: '30px'});
            }
    });
});
</script>
like image 451
nickpish Avatar asked May 25 '26 05:05

nickpish


1 Answers

You can use the screen-Object's height, width, availHeight and availWidth attributes.

In case you want to execute some code on screens smaller than 800px for example just do:

if (screen.width < 800){
// do stuff
}

Be aware that this is an area that has some cross-browser pitfalls (and problems when having sth like the stumbleupon toolbar), so an alternative would be using jQuery (that you are already using) to detect your client's window size:

if ($(window).width() < 800){
// do stuff
}

Further reading at MDN regarding pure JS and jquery.com for the jQuery part

like image 76
m90 Avatar answered May 27 '26 19:05

m90