简体   繁体   中英

how to stop a sticky javascript from running on small screen sizes?

Both menubar and sidebar of my site are sticky. But when screen size is less than 700px all div are displayed in one column. I have done this with css media queries. Menubar is displayed on top , mainbar in middle and sidebar at bottom. So when page (which has maximum-width=700px) is scrolled down to 150px then menubar sticks to top and thus mainbar is hidden due to sticky menubar. And when sidebar comes it also sticks to top.

This is the javascript:

<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'/>
<script src='sticky.js' type='text/javascript'/>
<script>
    $(document).ready(function(){
        $("#menu,#sidebar").sticky({topSpacing:0});
    });
</script>

Please help me in this sticky situation. I want, when screen size is less than 700px then menubar and sidebar will become non-sticky.

Using media queries, you could do something like this:

<script>
    $(document).ready(function() {
        if(window.matchMedia('(min-width: 700px)').matches) {
            $("#menu,#sidebar").sticky({topSpacing:0});
        }
    });
</script>

This is assuming that the only thing that makes them sticky is this JS function.

You could also use $(window).height() > 700 instead of window.matchMedia('(min-width: 700px)').matches .

You could do it with css media queries. Enforce position of #menu and #sidebar be static when the screen width is less than 700px. Because sticky does its job by changing their position to fixed .

<style>
@media (max-width: 699px) {
  #menu,#sidebar{
    position: static !important;
  }
}
</style>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'/>
<script src='sticky.js' type='text/javascript'/>
<script>
    $(document).ready(function(){
        $("#menu,#sidebar").sticky({topSpacing:0});
    });
</script>

...when screen size is less than 700px then menubar and sidebar will become non-sticky...

Let us reverse that. How about: "...when screen size is more than 700px then menubar and sidebar will become sticky..."?

I suggest checking the screen resolution, and only add sticky when the screen is more than 700px. Specifically:

<script>
    $(document).ready(function(){
        if ($(window).height() > 700) {
            $("#menu,#sidebar").sticky({topSpacing:0});
    });
</script>

Best regards,

Tim.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM