Skip to content
Advertisement

Using the duration of mouse press for scrolling

I coded this:

$("#scroll-to-left-button").on("mousedown", function() {
  var x = $("#scroll-area").scrollLeft();
  $("#scroll-area").scrollLeft(x - 10);
});


$("#scroll-to-right-button").on("mousedown", function() {
  var x = $("#scroll-area").scrollLeft();
  $("#scroll-area").scrollLeft(x + 10);
});
#container {
  width: 50%;
  height: 100px;
  background-color: grey;
  position: relative;
}

#scroll-area {
  white-space: nowrap;
  overflow-x: auto;
  height: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div id="container">
  <div id="scroll-area">
    <div id="text">Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.</div>
  </div>
</div>

<button id="scroll-to-left-button">Scroll to left</button>
<button id="scroll-to-right-button">Scroll to right</button>

You need to click the buttons pretty often to navigate through this container. Is there a way to let it based on the duration of the mouse press? Like if you keep the mouse pressed, it continues constantly scrolling? And if you stop, it stops.

Would be happy if someone could help me.

Advertisement

Answer

Here’s a working solution. Also your code was a bit wet, so I refactored it a bit. You only need one mousedown event listener.

let interval;

$('.scroll-btn').on('mousedown', ({ target }) => {
    const type = $(target).attr('id');

    interval = setInterval(() => {
        var x = $('#scroll-area').scrollLeft();
        $('#scroll-area').scrollLeft(type === 'left' ? x - 10 : x + 10);
    }, 50);
});

$('.scroll-btn').on('mouseout mouseup', () => clearInterval(interval));
#container {
    width: 50%;
    height: 100px;
    background-color: grey;
    position: relative;
}

#scroll-area {
    white-space: nowrap;
    overflow-x: auto;
    height: 100%;
}
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<div id="container">
    <div id="scroll-area">
        <div id="text">
            Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat,
            sed diam voluptua.
        </div>
    </div>
</div>

<button id="left" class="scroll-btn">Scroll Left</button>
<button id="right" class="scroll-btn">Scroll Right</button>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement