Answer the question
In order to leave comments, you need to log in
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:
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);
}
$("#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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question