I want to move a div inside another div when scrolling down. I want the div to only move side to side only when the div is on screen and only to move from one side to another inside the ".boatFlex2" boundaries. (that the blue part..)
$(document).ready(function () { var $horizontal = $('#horizontal'); $(window).scroll(function () { var s = $(this).scrollTop(), d = $(document).height(), c = $(this).height(); scrollPercent = (s / (d - c)); var position = (scrollPercent * ($(document).width() - $horizontal.width())); $horizontal.css({ 'left': position }); }); });
.section{ height: 100vh; width: 100%; background-color: pink; position: relative: }.boatFlex1{ width: 100%; height: 100px; position: relative; display: flex; background-color: green; justify-content:center; align-content: center; }.boatFlex2{ width: 47%; height: 100px; position: absolute; background-color: #090080; } #horizontal { position: absolute; width: 50px; background: red; left: 0px; top: 50px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script> <div class="section"> </div> <div id="boatFlex1" class="boatFlex1"> <div id="boatFlex2" class="boatFlex2"> <div id="horizontal">test</div> </div> </div> <div class="section"> </div>
Fiddle here
Compute the new position using:
var position = (scrollPercent * ($horizontal.position().left + $horizontal.width()));
and set #horizontal position to relative
var $horizontal = $('#horizontal'); $(window).scroll(function () { var s = $(this).scrollTop(), d = $(document).height(), c = $(this).height(); scrollPercent = (s / (d - c)); var position = (scrollPercent * ($horizontal.position().left + $horizontal.width())); $horizontal.css({ 'left': position }); });
.section { height: 100vh; width: 100%; background-color: pink; position: relative: }.boatFlex1 { width: 100%; height: 100px; position: relative; display: flex; background-color: green; justify-content: center; align-content: center; }.boatFlex2 { width: 47%; height: 100px; position: absolute; background-color: #090080; } #horizontal { position: relative; width: 50px; background: red; left: 0px; top: 50px; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <div class="section"> </div> <div id="boatFlex1" class="boatFlex1"> <div id="boatFlex2" class="boatFlex2"> <div id="horizontal">test</div> </div> </div> <div class="section"> </div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.