I am writing a Javascript code to automatically move the top Bar items to the right item...
I have categories in the top Bar, every category has a section in the body while I am scrolling vertically to this section I want the top bar to automatically scroll to this section name (category name).
while I'm using the scroll mouse button it's moving, but when I'm using the mobile's touch it's not.
Where is the bug in this code
My code is:
$(document).ready(function () {
// Cache selectors
var topMenu = $("#mainNav"),
topMenuHeight = topMenu.outerHeight() + 1,
// All list items
menuItems = topMenu.find("a"),
scrollItems = menuItems.map(function () {
var item = $($(this).attr("href"));
if (item.length) { return item; }
});
menuItems.click(function (e) {
var href = $(this).attr("href"),
offsetTop = href === "#" ? 0 : $(href).offset().top - topMenuHeight + 1 - 70;
$('html, body').stop().animate({
scrollTop: offsetTop
}, 150);
e.preventDefault();
});
// Bind to scroll
$(window).scroll(function () {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function () {
if ($(this).offset().top - 150 < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
// console.log(cur);
var id = cur && cur.length ? cur[0].id : "";
// // Set/remove active class
menuItems
.removeClass("active");
$('ul li a[href="#' + id + '"]').addClass("active");
////////////////////////////////////////////////////////
// the issue is here
var element = $("ul li a.active");
if (element.length)
element[0].scrollIntoView({ behavior: "smooth", inline: "end" });
////////////////////////////////////////////////////////
});
});