Source Source - 4 months ago 8
CSS Question

creating a constant instead of a variable for moving positions

I have element I wish to make a fixed position when it has been scrolled to. I can do this fine, my issue is, how do I remove the fixed position?

I am currently finding the position to fix the element when scroll has reached offset top of the element. The issue is, I can no longer get this number for the offset top of the element, as it is now fixed, the number changes when you scroll. So how can I keep this as a constant, I tried using const and var, but difference.

scroll = $(window).scrollTop();

function tb_fix() {
if($('#report_toolbar').length) {
const POS = $('#report_toolbar').offset().top;
if(scroll >= POS) {
$('#report_toolbar').addClass('fixed');
$('#tb_spacer').show();
} else if(scroll < POS && $('#report_toolbar').hasClass('fixed')) {
$('#report_toolbar').removeClass('fixed');
$('#tb_spacer').hide();
}
}
}

Answer

Below your toolbar, you have your #tb_spacer. This will still be a static element with constant offset. Try this:

function tb_fix() {
    if($('#report_toolbar').length) {
        pos = $('#report_toolbar').offset().top;
        pos2 = $('#tb_spacer').offset().top;
        if(scroll >= pos) {
            $('#report_toolbar').addClass('fixed');
            $('#tb_spacer').show();
        } 
        if(scroll < pos2 && $('#report_toolbar').hasClass('fixed')) {
            $('#report_toolbar').removeClass('fixed');
            $('#tb_spacer').hide();
        }
    }
}
Comments