Description
I have a div with several elements inside which are in sum longer than the div itself. See the following snippet for better understanding:
Code
.boxSlider { width: 100%; overflow-x: auto; white-space: nowrap; display: inline-block; }.box { display: inline-block; background-color: cyan; width: 100px; }
<div class="boxSlider"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <div class="box">Box 4</div> <div class="box">Box 5</div> <div class="box">Box 6</div> <div class="box">Box 7</div> <div class="box">Box 8</div> <div class="box">Box 9</div> <div class="box">Box 10</div> </div> <input type="Button" value="Scroll left"/> <input type="Button" value="Scroll right" />
Expected output
I want to use the buttons to scroll left or right using jquery or plain javascript.
You can use element.scroll(...) in order to accomplish what you want:
Some notes:
element.left += 50
but you lose the smooth feature which, in my opinion, is more user-friendly. In other hand, is compatible with all browsers . const boxSlider = document.getElementById('boxSlider'); document.getElementById("btnLeft").onclick = () => { boxSlider.scroll({ left: boxSlider.scrollLeft + 100, behavior: 'smooth' }); } document.getElementById("btnRight").onclick = () => { boxSlider.scroll({ left: boxSlider.scrollLeft - 100, behavior: 'smooth' }); }
.boxSlider { width: 100%; overflow-x: auto; white-space: nowrap; display: inline-block; }.box { display: inline-block; background-color: cyan; width: 100px; }
<div id="boxSlider" class="boxSlider"> <div class="box">Box 1</div> <div class="box">Box 2</div> <div class="box">Box 3</div> <div class="box">Box 4</div> <div class="box">Box 5</div> <div class="box">Box 6</div> <div class="box">Box 7</div> <div class="box">Box 8</div> <div class="box">Box 9</div> <div class="box">Box 10</div> </div> <input id="btnLeft" type="Button" value="Scroll left"/> <input id="btnRight" type="Button" value="Scroll right" />
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.