0

I've got a sticky sidebar going on with this code. But I only want it to affect the .fake-sidebar div when at 768px or below. Could anyone explain how to add media queries to my javascript?

var sticky_offset;
$(document).ready(function() {
    var original_position_offset = $('.fake-sidebar').offset();
    sticky_offset = original_position_offset.top;
    $('.fake-sidebar').css('position', 'fixed');
});

$(window).scroll(function () {
    var sticky_height = $('.fake-sidebar').outerHeight();
    var where_scroll = $(window).scrollTop();
    var window_height = $(window).height();     

    if((where_scroll + window_height) > sticky_offset) {
        $('.fake-sidebar').css('position', 'relative');
    }

    if((where_scroll + window_height) < (sticky_offset + sticky_height))  {
        $('.fake-sidebar').css('position', 'fixed');
    }
});

Any help is appreciated. Thanks in advance!

2
  • Personally, I think utilizing modernizr.com is the best route... Modernizr allows you to easily do exactly what you are asking to do. Commented Jul 31, 2013 at 1:30
  • Have you looked at window.matchMedia? sitepoint.com/javascript-media-queries Commented Jul 31, 2013 at 1:31

1 Answer 1

1

You can add the event on window resize, or on document ready, depending of what you want:

$(window).resize(function() {
        var width = $(window).width();
        if (width < 768) {
            $('.fake-sidebar').css('position', 'relative');
        }
        else {
            $('.fake-sidebar').css('position', 'fixed');
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.