Martin Martin - 3 months ago 16
jQuery Question

jQuery - Trigger event if a horizontally-scrollable div is at the left most and right most of scroll

I have a horizontally-scrollable div:

<div id = "scrollable-div">
<div class = "div-inside"></div>
<div class = "div-inside"></div>
<div class = "div-inside"></div>
<div class = "div-inside"></div>
</div>


I would like to trigger an event when the user scrolls to the extreme right of the div, and then another event when they scroll back to the extreme left of the div. I have the following code that triggers an event when I get to the extreme right:

jQuery(function ($) {
$('#scrollable-div').on('scroll', function () {
if ($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) {
$('#end-treatment').show();

}
})
});


But I can't seem to get it work when going back to the left. Basically, I would like to show one div when scrolled to extreme right and another when scrolled back to extreme left. Is this possible? Thanks..

Answer

Yes, if I'm understanding you correctly. See the code snippet below, but the basic idea is if($(this).scrollLeft() === 0) { ... }

I also inserted logic (see my comment) that hides the messages in case you wanted that, but you can remove it if that's not what you want.

jQuery(function ($) {
  $('#div-1').on('scroll', function () {
    if($(this).scrollLeft() + $(this).innerWidth() >= $(this)[0].scrollWidth) {
      $('#end-treatment').show();
    } else if($(this).scrollLeft() === 0) {
      $('#other-message').show();
      
    // Remove this part if you don't want your messages hidden again
    } else {
      $('#end-treatment').hide();
      $('#other-message').hide();
    }
  })
});
.scrollable-div {
  max-width: 200px;
  overflow-x: auto;
  white-space: nowrap;
  background: lightgray;
}

.div-inside {
  display: inline-block;
  width: 100px;
  height: 30px;
  margin-top: 10px;
  margin-bottom: 10px;
  background: gray;
}

.message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="div-1" class="scrollable-div">
  <div class="div-inside"></div>
  <div class="div-inside"></div>
  <div class="div-inside"></div>
  <div class="div-inside"></div>
</div>

<div id="end-treatment" class="message">
  "End Treatment"
</div>

<div id="other-message" class="message">
  "Other Message"
</div>

Comments