run jquery only on certain screen size?

var $sidebar   = $("#sidebar"), 
                $window    = $(window),
                offset     = $sidebar.offset(),
                topPadding = 15;

            $window.scroll(function() {
                if ($window.scrollTop() > offset.top) {
                    $sidebar.stop().animate({
                        marginTop: $window.scrollTop() - offset.top + topPadding
                    });
                } else {
                    $sidebar.stop().animate({
                        marginTop: 0
                    });
                }
            });

I'm using this script to enable sticky sidebar when scrolling thru a page but i want the sidebar to stay in a relative position when the screen size changes from desktop to mobile.

enter image description here

so when in mobile view, i want it to stay in a fixed relative psoition without the auto scrolling. like this:

enter image description here

It's not working properly with the script that i wrote. Any advice?

Answers 1

  • To get the width of the window you can do

     var w = window.innerWidth;
    

    So you can create some sort of conditional before you run the jquery for a certain screen size.

    if (window.innerWidth > 1200) // dont run jquery 
    

Related Articles