Skip to content

Instantly share code, notes, and snippets.

@kartick14
Created August 25, 2022 13:18
Show Gist options
  • Save kartick14/ca4426bb21b30c8c71c20cbdbad283a4 to your computer and use it in GitHub Desktop.
Save kartick14/ca4426bb21b30c8c71c20cbdbad283a4 to your computer and use it in GitHub Desktop.
Custom scrolling animations - pausing sections and scrolling elements horizontally
https://stackoverflow.com/questions/56713668/custom-scrolling-animations-pausing-sections-and-scrolling-elements-horizontal
<script>
$('.nested').each(function() {
let $window = $(window), $body = $('body');
let $nested = $(this), $nestedPlaceholder = $nested.parent();
let verticalScrollRange, upperMargin, lowerMargin;
$window.resize(function(){
$nested.removeClass("sticky").css({left: 0});
let placeholderHeight = $nestedPlaceholder.css({height: ''}).height();
verticalScrollRange = placeholderHeight - $window.height();
upperMargin = $nestedPlaceholder.offset().top;
lowerMargin = upperMargin + verticalScrollRange;
$nestedPlaceholder.height(placeholderHeight);
});
$window.scroll(function() {
let scrollTop = $window.scrollTop();
if (scrollTop > upperMargin && scrollTop < lowerMargin) {
$nested.addClass("sticky");
let horizontalScrollRange = $nested.width() - $body.width();
let verticalScrollPosition = scrollTop - upperMargin;
let horizontalScrollPosition = verticalScrollPosition / verticalScrollRange * horizontalScrollRange;
$nested.css({left: -horizontalScrollPosition});
} else {
$nested.removeClass("sticky");
}
});
$window.resize();
});
</script>
<style>
body {
background: linear-gradient(to bottom, #ffcb77 0%, #deaaff 100%);
}
.section {
height: 100vh;
font-size: 5em;
text-align: center;
position: relative;
border: 1px solid red;
}
.nested .section {
width: 100vw;
}
.nested-placeholder {
overflow: hidden;
}
.sticky {
position: fixed;
z-index: 1;
top: 0;
height: 100vh;
white-space: nowrap;
}
.sticky .section {
display: inline-block;
}
</style>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="section">Start scrolling down!</div>
<div class="section">slide 1</div>
<div class="nested-placeholder">
<div class="nested">
<div class="section first">slide 2</div>
<div class="section second">slide 3</div>
<div class="section third">slide 4</div>
</div>
</div>
<div class="section">slide 5</div>
<div class="section">slide 6</div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment