I am trying to make a horizontal transition when scrolling down and up to show and resize (shrink) div of the first element. I used inline-block to put them in the same position so that when one has been shrunk the other element will slide through but I am a bit confused to achieve this.
I tried to calculate the height and the offset position of the first inline element. This obviously will work for the first inline element but it won’t work on the second inline element because it’s in the same offset position.
Can you guys give me a bit of direction or tips to achieve this?
var topofDiv = $(".one").offset().top; var heightDiv = $(".one").outerHeight(); $(window).scroll(function() { if ($(window).scrollTop() > (topofDiv + heightDiv)) { $(".one").show(); } else { $(".one").hide(); } });
* { margin: 0; padding: 0; } body { overflow-x: hidden; } .container { width: 100vw; height: 100vh; } .content-wrapper { width: 100vw; white-space: nowrap; } .section { width: 100vw; height: 100vh; position: relative; display: inline-block; } .section div { font-size: 100px; color: white; position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); } .one { background-color: red; } .two { background-color: yellow; }
<div class="container"> <div class="content-wrapper"> <div class="section one"> <div>one</div> </div> <div class="section two"> <div>two</div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
Advertisement
Answer
The show()
and hide()
calls need to be swapped over, they’re in the wrong sides of your if
condition. Also, the page height needs to be greater than the height of one of the .section
elements for the transition to work properly, and the .container
needs to be in fixed
position for the scroll to have no effect on it. Try this:
var topofDiv = $(".one").offset().top; var heightDiv = $(".one").outerHeight(); $(window).scroll(function() { if ($(window).scrollTop() > (topofDiv + heightDiv)) { $(".one").hide(); } else { $(".one").show(); } });
* { margin: 0; padding: 0; } body { overflow-x: hidden; height: 2000px; } .container { width: 100vw; height: 100vh; position: fixed; } .content-wrapper { width: 100vw; white-space: nowrap; } .section { width: 100vw; height: 100vh; position: relative; display: inline-block; } .section div { font-size: 100px; color: white; position: absolute; top: 50%; left: 50%; transform: translateX(-50%) translateY(-50%); } .one { background-color: red; } .two { background-color: yellow; }
<div class="container"> <div class="content-wrapper"> <div class="section one"> <div>one</div> </div> <div class="section two"> <div>two</div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>