4

I know the question sounds confusing, but here is what I am trying to do - in the snippet below, if the user scrolls on the green div, I want the yellow div to be scrolled accordingly, just as if the yellow div was scrolled.

Note that the yellow div has overflow: auto; but the green one doesnt.

document.getElementById('green').addEventListener('wheel', function(e){

  console.log('scrolled!');

  console.log(e.deltaX); // it is always "-0"

  // scroll div#yellow accordingly

});
#yellow{
  background-color: yellow;
  display: inline-block;
  width: 200px;
  height: 200px;
  overflow: auto;
  vertical-align: top;
  padding 20px;
}

#green{
  background-color: green;
  display: inline-block;
  width: 100px;
  height: 200px;
  vertical-align: top;
}
<div id='yellow'>
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>4</p>
  <p>5</p>
  <p>6</p>
  <p>7</p>
  <p>8</p>
  <p>9</p>
  <p>10</p>
</div>

<div id='green'></div>

How do I achieve this?

Rahul Desai
  • 15,242
  • 19
  • 83
  • 138

2 Answers2

3

Try this DEMO

document.getElementById('green').addEventListener('wheel', function(e) {


  console.log(e.deltaY); // it is always "-0"

  // scroll div#yellow accordingly
  document.getElementById('yellow').scrollTop += e.deltaY;
});



#yellow {
  background-color: yellow;
  display: inline-block;
  width: 200px;
  height: 200px;
  overflow: auto;
  vertical-align: top;
  padding 20px;
}
#green {
  background-color: green;
  display: inline-block;
  width: 100px;
  height: 200px;
  vertical-align: top;
}



<div id='yellow'>
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>4</p>
  <p>5</p>
  <p>6</p>
  <p>7</p>
  <p>8</p>
  <p>9</p>
  <p>10</p>
</div>

<div id='green'>
  <p>1</p>
  <p>2</p>
  <p>3</p>
  <p>4</p>
  <p>5</p>


</div>
CY5
  • 1,551
  • 17
  • 23
2

You're trying to get the deltaX property, and what you need for vertical scrolling is the deltaY one.

document.getElementById('green').addEventListener('wheel', function(e){
  e.preventDefault();
  document.getElementById('yellow').scrollTop += e.deltaY * 10;
});
Buzinas
  • 11,597
  • 2
  • 36
  • 58
  • Wow, have been looking for this the past 6 hours. Just after fiddling with the perfect title for my own question I stack suggested me this question! I'm just curious how this solution would work with jQuery; `$(".green").on("wheel", function(e) ...` doesn't seem to have `e.deltaY`? – katerlouis Feb 17 '18 at 00:54