How to Scroll horizontal  Sub Menu  with Active Class while page scroll Using JavaScript


How to Scroll horizontal  Sub Menu with Active Class while page scroll Using JavaScript.

Hy Friends Today we will learn How to Scroll horizontal  Sub Menu with Active Class while page scroll Using JavaScript.

So let's Start

Notice - Please follow the steps

Step 1 -  Create A Sub Menu 

<div class="crd-scroll" id="sub-menuScroll">
<span class="sub-menu active" data-tab="sub-menu1">sub1</span>
<span class="sub-menu" data-tab="sub-menu2">sub2</span>
<span class="sub-menu" data-tab="sub-menu3">sub3</span>
<span class="sub-menu" data-tab="sub-menu4">sub4</span>
<span class="sub-menu" data-tab="sub-menu5">sub5</span>
<span class="sub-menu" data-tab="sub-menu6">sub6</span>
<span class="sub-menu" data-tab="sub-menu7">sub7</span>
<span class="sub-menu" data-tab="sub-menu8">sub8</span>
<span class="sub-menu" data-tab="sub-menu9">sub9</span>
<span class="sub-menu" data-tab="sub-menu10">sub10</span>
<span class="sub-menu" data-tab="sub-menu11">sub11</span>
</div>
Step 2 -  Css 
<style> .active { background:#ff5a00;} </style>

Step 3 - JavaScript

const  onScroll = () => {

var scrollPos = $(document).scrollTop();
    
$("#sub-menuScroll span").each(function () {

var currLink = $(this);
var el = this;
var refElement = $("#"+currLink.attr("data-tab"));
const elLeft = el.offsetLeft + el.offsetWidth;
const elParentLeft = el.parentNode.offsetLeft + el.parentNode.offsetWidth;

if (refElement.position().top <= scrollPos+120
 && refElement.position().top + refElement.height() > scrollPos+120) {
$('#sub-menuScroll span').removeClass("active");
currLink.addClass("active");
const elLeft = el.offsetLeft + el.offsetWidth;
const elParentLeft = el.parentNode.offsetLeft+el.parentNode.offsetWidth;

// check if element not in view
if (elLeft >= elParentLeft + el.parentNode.scrollLeft) {
el.parentNode.scrollLeft = elLeft - elParentLeft;

} else if (elLeft <= el.parentNode.offsetLeft + el.parentNode.scrollLeft) {

el.parentNode.scrollLeft = el.offsetLeft - el.parentNode.offsetLeft;
}

}


});
};
$(document).on("scroll", onScroll);
Notice -> Above code i have added 120 with scrollPos for my submenu you can give according to you
Yeah! You have learned ЁЯШК

I hope you understood and like this article. if you like it so, please give feedback in the comment section.



Post a Comment

Please do not enter any spam link in the comment section.

Previous Post Next Post