3

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>
1
  • Have you looked at the window.screen.availWidth attribute? Commented Aug 19, 2012 at 10:04

2 Answers 2

9

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks m90-- still a js beginner here; that was pretty straightforward!
0

You could place something like this in your scroll event callback.

If ($(window).width() < 1024) {
    return;
}

1 Comment

thanks for the response, Alex; where exactly would I place this within the function?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.