Home > database >  horizontal scrolling of div not working with scrollLeft
horizontal scrolling of div not working with scrollLeft

Time:01-23

I tried to make horizontal scrolling with scrollLeft. I'm able to align div horizontally but it looks like the scrollLeft function is not working.

Here is my code:

function myFunction() {
  var elmnt = document.getElementById("myDIV");
  elmnt.scrollLeft  = 50;
}
#myDIV {
  height: 250px;
  width: auto;
  display:inline-flex;
  gap:10px;
  overflow: auto;
}

#content {
  height: 800px;
  width: 200px;
  background-color: coral;
}
<button onclick="myFunction()">Scroll div</button><br><br>

<div id="myDIV">
  <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
</div>

Thank you for the help in advance!

CodePudding user response:

I applied the white-space and overflow style inside the #myDiv style; I set the width property to 220px to follow the scrollLeft[1].

function myFunction() {
  var element = document.getElementById("myDIV");
  element.scrollLeft  = 50;
}
#myDIV {  
  white-space: nowrap;
  overflow: scroll;
  width: 220px;
  height: 250px;
  display: inline-flex;
  gap: 10px;
}
#content {
  height: 800px;
  width: 200px;
  background-color: coral;
}
<button onclick="myFunction()">Scroll div</button><br><br>

<div id="myDIV">
  <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
    <div id="content">
  Some text inside a div element.<br><br>
  Some text inside a div element.
  </div>
</div>


1 - JavaScript element.scrollLeft not working

  •  Tags:  
  • Related