Or can someone tell me another way to do this (without using a plugin please)
I have a side nav on the left and some content to the right. Both elements are floated left.
I want the side nav to 'stick' when it gets to 125px from the top of the window, once scrolled down the page.
I feel like I'm close, but I'm definitely not there yet! With the code I have written, the side-nav 'jumps' up to the top of the window once we scroll to the correct window position and then it's going back to the position where I want it to 'stick'.
The other issue, is that once the .stick class is applied, the element is taken out of the document flow (because I'm applying a position: fixed;) and the .content moves over to the left to take it's place.
Here is a codepen: http://codepen.io/MandyMadeThis/pen/DLtsJ
** NOTE: It seems I can't recreate the side-nav 'jumping' to the top of the window on scroll, so I don't what that's all about, but I'd still like to know the correct way to do this without the content moving over to the left.**
If anyone can guide me in the right direction, that would be wonderful. Thank you.
Here is my markdown:
<body>
<nav>navigation content</nav>
<header>header content</header>
<div class="container clearfix">
<div class="side-nav">THIS IS THE THING I WANT TO STICK</div>
<div class="content">This needs to stay to the right of the .side-nav</div>
</body>
Here is the CSS:
.side-nav {
float: left;
position: relative;
top: -17px;
width: 23%;
margin-right: 2%;
}
.content {
width: 70%;
float: left;
}
.stick {
position:fixed;
top:0px;
margin-top: 125px;
}
And here is my jQuery:
var sn = $(".side-nav");
var pos = sn.position();
$(window).scroll(function() {
var windowPos = $(window).scrollTop();
if (windowPos >= pos.top - 125) {
sn.addClass("stick");
} else {
sn.removeClass("stick");
}
});
To fix this you simply need to add a margin-left
to .content
and remove float
. This way the position of the content does not rely on the nav being there.
.content {
width: 70%;
margin-left: 25%;
}