j00m
j00m

Reputation: 501

Fixed header logic

I am fixing a header to the page when the user scrolls to beyond the header itself.

There is another condition that a checkbox be clicked before it shows. The checkbox class is "list-item". This is working fine.

The third part of this is. If the user scrolls and THEN clicks on a checkbox the header needs to appear/disappear on that condition. Obviously my function is all based onscroll and I'm not sure how to build this functionality in.

    stickyUseTools : function() {
        var stickyTools = $j('#sticky-usetools');
        if (stickyTools.length > 0 && window.outerWidth > 425) {
            var headerHeight = stickyTools.height();
            var fixmeTop = stickyTools.offset().top + headerHeight - 50;
            $j(window).scroll(function() {
                var currentScroll = $j(window).scrollTop();
                if (currentScroll >= fixmeTop && ($j(".list-item").length == 0 || $j(".list-item:checked").length > 0)) {
                    stickyTools.addClass('sticky');
                } else {
                    stickyTools.removeClass('sticky');
                }
            });
        }
    }
};

Upvotes: 0

Views: 114

Answers (2)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11086

Define a (localy) global boolean variable and update it as the checkbox was changed:

var checkBoxStatus=false;

// Initiate the variable if you want to be true:

$j(document).ready(function(){
    if ($j(".list-item").length == 0){ 
        checkBoxStatus=true;
    }
})

//Listen to checkbox changes
$j(".list-item").change(function(){
    if ($j(".list-item:checked").length > 0){ 
        checkBoxStatus=true;
    }else{
        checkBoxStatus=false;
    }

    // Trigger a fake scroll event to dispatch new changes
    // $j(document).get(0).dispatchEvent(new Event('scroll'));
    // If the above code not works try this:
    window.scrollTo(window.scrollX, window.scrollY - 1);
    window.scrollTo(window.scrollX, window.scrollY + 1);
})

Finally replace the checkBoxStatus in the logic:

stickyUseTools : function() {
    var stickyTools = $j('#sticky-usetools');
    if (stickyTools.length > 0 && window.outerWidth > 425) {
        var headerHeight = stickyTools.height();
        var fixmeTop = stickyTools.offset().top + headerHeight - 50;
        $j(window).scroll(function() {
            var currentScroll = $j(window).scrollTop();
            if (currentScroll >= fixmeTop && checkBoxStatus) {
                stickyTools.addClass('sticky');
            } else {
                stickyTools.removeClass('sticky');
            }
        });
    }
}

Upvotes: 1

Obzi
Obzi

Reputation: 2390

You can do it with mainly CSS.

  1. Add/remove class to #sticky-usetools depending if the checkbox is checked
  2. Apply position: sticky; top: 0; to #sticky-usetools if it has the previous class

https://caniuse.com/#feat=css-sticky

PS: depending of the needed compatibility

Upvotes: 0

Related Questions