htmlcssoverflowhorizontal-scrolling

make a button to scroll horizontally in div


I have a website where I have a div with images in it, set to overflow:auto; white-space: nowrap; So you can scroll horizontally in the div to see all the images in it.

Can I make two buttons (left and right) to scroll this div horizontally? I ask this because when I have a touchscreen or trackpad, I can scroll in the div but when I am on a desktop with only a mouse there is no option to scroll the div. And I hear you thinking just use the scrollbar but I have hidden those using CSS because they look different on different computers and browsers and were just a complete pain and didn't look clean enough for me. Here is my site (I made a page where I explain the problem again).

I have watched for carousel plugins but want to know if there's a way with CSS.

.blackbackgroundscroll {
   background: #fff;
   padding: 8px 8px 8px 8px;
   margin: 12px 0px 5px 0px;
   box-shadow: 0 0px 0px 0 rgba(0,0,0,0.0);
   border: 1px solid #dadce0;
   border-top-left-radius: 2px;
   border-top-right-radius: 2px;
   border-bottom-right-radius: 2px;
   border-bottom-left-radius: 2px;
   overflow: auto;
   white-space: nowrap;
   -webkit-overflow-scrolling: touch;
 }
<div class="blackbackgroundscroll">
  <a href="https://www.npostart.nl/pauw/VARA_101377247" target="_blank" rel="noopener noreferrer">
  <img src="https://tuberadar.nl/wp-content/uploads/PAUW-thumbnail.png" alt="" width="210" height="119" class="alignleft size-full wp-image-16930" />
  </a>
</div>

I have no idea where to start, because I also have the feeling this is going to need some JavaScript and I have no experience with JS.


Solution

  • You can scroll using Element.scrollLeft property to which you can provide the amount to scroll as an integer value.

    Here is a basic example: JavaScript + CSS + HTML

        const buttonRight = document.getElementById('slideRight');
        const buttonLeft = document.getElementById('slideLeft');
    
        buttonRight.onclick = function () {
          document.getElementById('container').scrollLeft += 20;
        };
        buttonLeft.onclick = function () {
          document.getElementById('container').scrollLeft -= 20;
        };
        #container {
          width: 145px;
          height: 100px;
          border: 1px solid #ccc;
          overflow-x: scroll;
        }
    
        #content {
          width: 250px;
          background-color: #ccc;
        }
        <div id="container">
          <div id="content">Click the buttons to slide horizontally!</div>
        </div>
        <button id="slideLeft" type="button">Slide left</button>
        <button id="slideRight" type="button">Slide right</button>