0

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" });

////////////////////////////////////////////////////////

  });
});
IAfanasov
  • 4,775
  • 3
  • 27
  • 42
  • After googling a while I figured out that ScrollIntoView behavior: "smooth" it's not supported in all browsers, How can I get ScrollIntoView to move smoothly... when I am using block: "center" it's working but not moving smoothly is there a way to make it smooth ? – Ayman Ghandour Jun 17 '21 at 00:57
  • I hope it may help you https://stackoverflow.com/questions/18064270/scrolling-on-mobile-devices . Thanks. – Muthulakshmi M Jun 17 '21 at 02:16

0 Answers0