A
A
Alexander2017-04-29 08:10:00
JavaScript
Alexander, 2017-04-29 08:10:00

How to simulate a scroll event?

It is necessary to simulate a scroll event so that the page scrolls as it would with normal mouse scrolling.
Other scrolling options are not suitable. I'm interested in exactly simulating a mouse scroll event with the necessary parameters set.
I would be very grateful if you could help me find a way to do this.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Di Ma, 2017-04-29
@dimentimor

The scroll- event does not change the scrollTop value. This will have to be done by yourself.
But the event itself can be generated and "caught", including passing the necessary values ​​with it.

var body = document.getElementsByTagName('body')[0];

// по клику 
window.addEventListener('click', function (e) {

  // создадим кастомное событие типа scroll
  var event = new CustomEvent("scroll", {
    detail: {
      scrollTop: 200 // передадим нужные значения
    }
  });
  // "вызовем" событие
  window.dispatchEvent(event);
});

// добавим слушателя события scroll
window.addEventListener('scroll', function (e) {
  console.log(e);
  // если событие не настоящее
  if (!e.isTrusted) {
    body.scrollTop = e.detail.scrollTop; // изменяем scrollTop на переданное значение
  }
});

Now on click the page will scroll by 200 px. And all scroll listeners will "hear" the event.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question