I am currently working on a portfolio website project using HTML, CSS, PHP and JavaScript. I have almost completed it. There is one issue I am facing and having hard time fixing it. So I have made sticky navigation bar using IntersectionObserver. And I have made the website responsive. So the sticky navigation bar is working fine with all the screens except for smaller mobile screens.
So basically I have attached IntersectionObserver to home section and it works fine for big screens by throwing one Intersecting entry and displaying the sticky navigation, but for smaller screens as soon as I reach about-section , it keeps throwing unlimited entries ('I checked them in console'). And I am not able to find why is it happening. A help will be much appreciated.
Here is the link to the project
, Just go to smaller screen where you can see hamburger menu icon and then try going just to the start of about-section, the screen will keep shaking until you move the scroll from that position.
I think the original problem was the continuous invocation of the intersectionobserver.
This seemed to occur exactly when the bottom of the target touched/was just 1 pixel above the top of the root.
The 2 areas were not overlapping but touching.
Target bottom was on pixel 100 and root top was on pixel 101 for example.
Now, the intersectionobserver has 2 if statements which causes the body element to have a 'nav-scrolled' class added/removed to/from it.
This adding of the class "nav-scrolled" causes this css rule to be matched "nav-scrolled .nav-bar".
That rule causes position fixed of the nav-bar.
It is actually quite difficult to scroll so the target and the root touch at the borders.
I think a different solution would be to make the threshold in the intersectionobserver option be 0.01.
Originally the threshold was 0 - zero, which means the io is called when at least 1 pixel intersects the root.
I think this intersection can include being adjacent.
The added class seems to slightly change the position of some elements.
So one solution could be to change the threshold.
I chose to adjust the callback code which seems more robust.
This code checks the bottom edge of the target and the top of the root.
if(entry.boundingClientRect.bottom < entry.rootBounds.top){
body.classList.add("nav-scrolled");
}else{
body.classList.remove("nav-scrolled");
}
replace
if (!entry.isIntersecting) {
body.classList.add("nav-scrolled");
}
if (entry.isIntersecting) {
body.classList.remove("nav-scrolled");
}