bigspotteddog / ScrollToFixed

This plugin is used to fix elements on the page (top, bottom, anywhere); however, it still allows the element to continue to move left or right with the horizontal scroll.
http://bigspotteddog.github.com/ScrollToFixed/
MIT License
1.81k stars 532 forks source link

detach trigger not working #222

Open laureljanej opened 8 years ago

laureljanej commented 8 years ago

Thanks for the great plugin!

I'm having an issue with the detach trigger not unfixing the sticky header when called. I'm calling it from a custom function because I'm calculating the height of submenus so that the header is fixed when the menu fits in the viewport but unfixed when the menu doesn't fit.

The detach trigger is called when the window is resized (and smaller than the height of the menus) but it doesn't unfix the header.

Here's my code:

function stickyHeader() {
    var ViewportHeight;
    var HeaderHeight;
    var MenuHeight;

    ViewportHeight = $(window).height();
    HeaderHeight = $(".header").height();
    MenuHeight = 0;

    // if main menu is active, get height of longest submenu
    if ( $("#menu-main-menu").height()!=0 ) {
        $("#menu-main-menu .sub-menu").each(function(){
            var Height = $(this).height();
            if ( Height > MenuHeight ) {
                MenuHeight = Height;
            }
        });
    } 
    // else use height of mobile menu"s longest submenu
    else {
        $("#menu-mobile-menu .sub-menu").each(function(){
            var Height = $(this).height();
            if ( Height > MenuHeight ) {
                MenuHeight = Height;
            }
        });
    }
    var menu = HeaderHeight + MenuHeight;
    // make the menu sticky if fits inside window
    if ( (HeaderHeight + MenuHeight) < ViewportHeight ) {
        $(".header").scrollToFixed();       
    } else {
        $(".header").trigger("detach.ScrollToFixed");
    }
}

$(window).on("load", function(){
    stickyHeader();
    window.addEventListener("resize", function() { stickyHeader(); console.log("resizing"); });
});
laureljanej commented 8 years ago

I was able to solve this by resetting the inline styles on the fixed element after detaching ScrollToFixed. It'd be great if clearing the styles could be part of the native detach function because the inline styles continue to make the element sticky even after detaching the plugin.

$('#scroll_fixed').trigger('detach.ScrollToFixed');
$('#scroll_fixed').attr("style","");