make a button to scroll horizontally in div

Amsterdam_020 picture Amsterdam_020 · May 31, 2019 · Viewed 16.2k times · Source

Thank you for reading my question.

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. My question. 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 didnt look clean enough for me. Here is my site (i made a page where i explain the problem again.) https://tuberadar.nl/test1234/

Thank you for reading my question.

Have a nice day!

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;
     }

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.

Answer

Vlad Danila picture Vlad Danila · May 31, 2019

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>