Home » Jquery » jquery – Scroll child div edge to parent div edge

jquery – Scroll child div edge to parent div edge

Posted by: admin February 22, 2020 Leave a comment

Questions:

It’s fine horizontal scrolling. But I expect that when scrolling, each of child div’s edge get stuck to parent div’s edge. So child div visible proper and not get hidden it’s any portion. Please see my below code.

jQuery(function($) {
  $.fn.hScroll = function(amount) {
    amount = amount || 50;
    $(this).bind("DOMMouseScroll mousewheel", function(event) {
      var oEvent = event.originalEvent,
        direction = oEvent.detail ? oEvent.detail * -amount : oEvent.wheelDelta,
        position = $(this).scrollLeft();
      position += direction > 0 ? -amount : amount;
      $(this).scrollLeft(position);
      event.preventDefault();
    })
  };
});

$(document).ready(function() {
  $('#box').hScroll(50); // You can pass (optionally) scrolling amount
});
body {
  margin: 0;
  padding: 0;
}

.container {
  display: flex;
}

#box-left {
  min-width: 50%;
  height: 100vh;
  background: #E6E6E6;
}

#box {
  display: flex;
  display: -webkit-flex;
  width: 50vw;
  height: 100vh;
  align-items: center;
  overflow-x: hidden;
}

.item {
  display: table-cell;
  min-width: 50vw;
  height: 100vh;
  font-size: 140px;
  text-align: center;
}

.item:nth-child(odd) {
  background: #1D5D95;
}

.item:nth-child(even) {
  background: #CCCCCC;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
  <div id="box-left">left box</div>
  <div id="box">
    <div class="item">1</div>
    <div class="item">2</div>
    <div class="item">3</div>
    <div class="item">4</div>
    <div class="item">5</div>
    <div class="item">6</div>
    <div class="item">7</div>
    <div class="item">8</div>
    <div class="item">9</div>
  </div>
</div>
How to&Answer: