Im trying to create an effect than when my user scrolls, my h1
sticks to the top of the window. When the parent div has scrolled past the h1 is then 'released' and scrolls again as normal. When my next section
comes in I'd then like to stick that next h1
to the top again and so on.
Fiddle
jQuery
$(document).ready(function(){
$(window).scroll(function(){
$('section h1').addClass('fixed');
})
})
I've also tried :
var section = $('section');
distance = section.offset().top,
$window = $(window);
$window.scroll(function() {
if ( $window.scrollTop() >= distance ) {
section.find('h1').addClass('fixed');
}
});
The vertical position of the element to be stuck can also be modified with the help of the 'top' property. It can be given a value of '0px' to make the element leave no space from the top of the viewport, or increased further to leave space from the top of the viewport.
Just replace #sticky_div's_name_here with the name of your div, i.e. if your div was <div id="example"> you would put #example { position: sticky; top: 0; } .
You can do this using a bit of jQuery.
The following snippet calculates the offset of each section to the top of the window. When a section hits the top of the window, it's title <h1>
position is changed to position:fixed;
.
jQuery:
function fixTitle() {
$('section.affix').each(function () {
var $this = $(this);
var offset = $this.offset().top-40;
var scrollTop = $(window).scrollTop();
if (scrollTop > offset) {
$this.addClass('fixed');
} else {
$this.removeClass('fixed');
}
});
}
$(document).ready(function () {
$(window).scroll(fixTitle);
});
CSS:
section {
overflow:hidden;
padding:0 20%;
position:relative;
text-align:justify;
}
section h1 {
float:left;
width:14%;
padding-left:1.5%;
line-height:40px;
background:#fff;
position:relative;
z-index:1;
}
section .summary {
float:right;
width:70%;
}
.fixed h1:first-child {
position:fixed;
top:0;
}
h1:first-child:before{
content:"";
position:absolute;
left:0;
width:5%;
height:100%;
background-color:#4381B6;
z-index:-1;
}
.fixed h1:first-child:before{
width:100%;
-webkit-transition:width 0.5s ease-in-out;
transition: width 0.5s ease-in-out;
}
You can solve this with CSS3 in some of the most recent browsers by using
.sticky {
position: -webkit-sticky;
position: -moz-sticky;
position: -ms-sticky;
position: -o-sticky;
position: sticky;
top: 15px;
}
See this demo (or this demo with a polyfill in browsers that do not support position:sticky natively) and the corresponding article to find out more. I would suggest using this technique as it works without any issues (even on mobile devices) and a robust polyfill for older browser is already available.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With