Brooklyn Based Web Development

Fixed Positioning and Sticky Elements

Dec
17
2014

I’m putting the final touches on a recent responsive website design project in Drupal and have made a new discovery on sticky items and fixed positioning. Typically “Sticky” elements are set as fixed positioning items. But what happens when you need to create an element that is both sticky and part of the document flow? Position: Fixed removes the element from the natural flow of the document. A solution to this was use Jquery to dynamically change the position of the element by way of onScroll event listeners and margin-top calculations. Nice solution, it works beautifully on Firefox, Chrome and WebKit browsers, but Safari and IE fell short. The element calculation that smoothly moved up and down the page as the user scrolls, was herky jerky all over the place on the Safari browsers. You’ve seen the workarounds on the web for quite some time… Delayed stickiness with relative positioning… Solves the problem for Safari and IE!

Here’s an interesting article on some useful stickiness plugins. Although none of these solutions deal with content that must be kept relative positioned, they’re useful tools in front-end development.

http://www.sitepoint.com/10-jquery-sticky-scroll-plugins/

Also: The great folks at Filament Group have created a solution with polyfills and a fallback to support back to IE7.
https://github.com/filamentgroup/fixed-sticky

 

$(window).scroll(function(e) {
    var contentHeight = $('#main').height();
    var contentHeight1 = contentHeight + 136;
    var position = window.pageYOffset;
    var calc = position + 136; 
    var calculation = calc + 'px'; 
    var show_width = $(window).width();

    if (show_width > 768) {
        if ($(window).scrollTop() < contentHeight1) {
            setTimeout(function (){
            $('.safari #block-menu-block-1').css('marginTop',calculation); 
            $('.safari #block-block-1').css('marginTop',calculation); 
            $('.ie #block-menu-block-1').css('marginTop',calculation); 
            $('.ie #block-block-1').css('marginTop',calculation); 
        }, 60);

        $('html:not(.safari,.ie) #block-menu-block-1').css('marginTop',calculation);
        $('html:not(.safari,.ie) #block-block-1').css('marginTop',calculation);
       }
     }
});