V
V
Vadim Kontarev2021-07-03 19:27:37
JavaScript
Vadim Kontarev, 2021-07-03 19:27:37

How to make automatic horizontal scroll to the desired element?

The question seems to be simple, but I've been scratching my head over it for a week now:
There is a long page (two-page site) divided into sections. Each section has its own title, duplicated in the header. When scrolling to a specific section (any section), its title in the header is highlighted as active, everything is fine with that.
Difficulties arise when the header overflows: I made a horizontal scroll, and now the task is to automatically scroll to the selected header of the current section. I tried in various ways to determine the desired scroll position, but all to no avail ...

Now I settled on this option:

The code
max_sp = 0;
if ($("#menu-mobile").width() > 0) {
  $("#menu-mobile").scrollLeft(0);
  var max_sp = $("#menu-mobile .menu-item").last().position().left + $("#menu-mobile .menu-item").last().width();
} else if ($("#menu-tablet").width() > 0) {
  $("#menu-tablet").scrollLeft(0);
  var max_sp = $("#menu-tablet .menu-item").last().position().left + $("#menu-tablet .menu-item").last().width();
} else if ($("#menu-desktop").width() > 0) {
  $("#menu-desktop").scrollLeft(0);
  var max_sp = $("#menu-desktop .menu-item").last().position().left + $("#menu-desktop .menu-item").last().width();
}

scroll_percent = $(window).scrollTop() / $(document).height();
sp = max_sp * scroll_percent;

if (sp < 0) {
  $('.menu-limiter').animate({scrollLeft: "0px"}, 200);
} else {
  $('.menu-limiter').animate({scrollLeft: sp+"px"}, 200);
}

But I still have artifacts in the form of spontaneous automatic scrolling (possibly due to selection, where the font becomes bold). The value Suddenly turns out to be undefined, so I did such a perversion:
$("#menu-desktop").scrollWidth
var max_sp = $("#menu-desktop .menu-item").last().position().left + $("#menu-desktop .menu-item").last().width();

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
Vladimir, 2021-07-03
@HistoryART

Anchors to help, write to the id variable and hang the handler.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question