Alaric Alaric - 4 months ago 15
CSS Question

Element that fixes position on scroll jumps out of place on page load

I am making a blog page with bootstrap. The right hand third of the page is a column with a categories list and search bar that becomes fixed when you scroll 300px from the top of the page. This seems to function well but the issue is that when the page is first loaded, the side element jumps to the top of the page for no apparent reason. I assume there is something wrong with my JS code.

$(window).scroll(function() {
var scroll = $(window).scrollTop();
var objectSelect = $("#wrapnews");
var objectPosition = objectSelect.offset().top;
if (scroll > 300) {
$(".col-md-4").addClass("fix-sidebar");
} else {
$(".col-md-4").removeClass("fix-sidebar");
}
});


Here is the CSS for further reference

.fix-sidebar {
position: fixed !important;
top: 180px;
right: 30px;
width: 360px;
}

.sidenote {
text-align: center;
display: block;
background-color: #ccc;
color: #fff;
border: 2px solid #000;
border-radius: 2px;
width: 360px;
}


And the nesting of the HTML divs

<div class="col-md-4 fix-sidebar" id="wrapnews">
<div class="sidenote">
</div>
</div>

Answer

AS col-md-4 is left float, so you should't make it positon fixed.

And because you add position:fixed to .fix-sidebar, so you should remove right: 30px;.

var objectSelect = $("#wrapnews"), objectPosition = objectSelect.offset().top;
    $(window).scroll(function () {
        var scroll = $(window).scrollTop();
        if (scroll > objectPosition) {
            objectSelect.addClass("fix-sidebar");
        } else {
            objectSelect.removeClass("fix-sidebar");
        }
    });
@import url('//cdn.bootcss.com/bootstrap/3.3.5/css/bootstrap.min.css');

body {
        height: 2000px;
    }

    .wrapnews {
        position: relative;
        top: 180px;
    }

    .fix-sidebar {
        position: fixed !important;
        top: 0;
    }

    .sidenote {
        text-align: center;
        display: block;
        background-color: #ccc;
        color: #fff;
        border: 2px solid #000;
        border-radius: 2px;
        width: 360px;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="container">
    <div class="col-md-8" style="background: red;height: 1000px">
        content
    </div>
    <div class="col-md-4">
        <div class="wrapnews" id="wrapnews">
            <div class="sidenote">sidenote
            </div>
        </div>
    </div>
</div>
            

You can see a online demo HERE