Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scroll visible part of overflown div inside smaller div without jquery

I´m currently trying to move a wider div B horizontally inside an smaller <div> A using two buttons.
I found a similar problem using jquery, but doesn´t want to use the library just for this section in the code.

Here is the fiddle

I want to scroll the visible field of view using a 'left' and 'right' button to move the field 100px in either direction without using jquery but with pure Javascript, HTML and CSS.

<div id="outer-div" style="width:250px;overflow:hidden;">
  <div style="width:750px;">
    <div style="background-color:orange;width:250px;height:100px;float:left;">
    </div>
    <div style="background-color:red;width:250px;height:100px;float:left;">
    </div>
    <div style="background-color:blue;width:250px;height:100px;float:left;">
    </div>
  </div>
</div>
<button>left</button>
<button>right</button>
like image 576
JohnDizzle Avatar asked Nov 29 '17 14:11

JohnDizzle


2 Answers

var outerDiv = document.getElementById('outer-div');

function moveLeft() {
  outerDiv.scrollLeft -= 100;
}

function moveRight() {
  outerDiv.scrollLeft += 100;
}

var leftButton = document.getElementById('left-button');
var rightButton = document.getElementById('right-button');

leftButton.addEventListener('click', moveLeft, false);
rightButton.addEventListener('click', moveRight, false);
<div id="outer-div" style="width:250px;overflow:hidden;">
  <div style="width:750px;">
    <div style="background-color:orange;width:250px;height:100px;float:left;">
    </div>
    <div style="background-color:red;width:250px;height:100px;float:left;">
    </div>
    <div style="background-color:blue;width:250px;height:100px;float:left;">
    </div>
  </div>
</div>
<button id="left-button">left</button>
<button id="right-button">right</button>
like image 61
Canta Avatar answered Sep 21 '22 01:09

Canta


Well that is very easy if you modify the writable scrollLeft property:

document.getElementById('to-right').onclick = function() {
  document.getElementById('outer-div').scrollLeft += 100;
}

document.getElementById('to-left').onclick = function() {
  document.getElementById('outer-div').scrollLeft -= 100;
}
<div id="outer-div" style="width:250px;overflow:hidden;">
  <div style="width:750px;">
    <div style="background-color:orange;width:250px;height:100px;float:left;"></div>
    <div style="background-color:red;width:250px;height:100px;float:left;"></div>
    <div style="background-color:blue;width:250px;height:100px;float:left;"></div>
  </div>
</div>
<button id="to-left">left</button>
<button id="to-right">right</button>
like image 25
FcoRodr Avatar answered Sep 20 '22 01:09

FcoRodr