Reputation: 351
Here is my current code which does the following: When the user scrolls down past a certain point, a new class name is added to a sticky div. This functionally allows me to change the CSS of that element only when the user scrolls down to that point.
const el = document.querySelector(".myElement")
const observer = new IntersectionObserver(
([e]) => e.target.classList.toggle("is-pinned", e.intersectionRatio < 1),
{ threshold: [1] }
);
observer.observe(el);
What I would ALSO like to do is change the name of ANOTHER element at this same scroll point. What would be the best way to accomplish this? One idea I have is, use MutationObserver to look for a class name change. However it seems there should be a much simpler way to be able to simply make an additional change within this same piece of code I have here. By that I mean, simply add another statement to the function that fires here to trigger the current class change.
There is a specific span element where I'd like to add a similar class name toggle, just as seen here. But for this span element.
<span class="material-symbols-outlined hide-stuff-arrow">keyboard_double_arrow_up</span>
Ideally I'd be able to toggle one additional class name ("is-pinned-2"), on this particular element, at the exact same scroll point of the previously seen IntersectionObserver.
Then I'd be able to modify the CSS of this element to my liking, so its appearance changes only when the user has scrolled past a certain point.
What would be the best way to do this? Could I just add an additional statement into this existing chunk of code that just does a querySelector on the span element, then adds another class name to it? That would be the simplest way, if it's possible.
Thanks!
Upvotes: 1
Views: 616
Reputation: 26384
Open up the arrow function's body:
const observer = new IntersectionObserver(
([e]) => {
e.target.classList.toggle("is-pinned", e.intersectionRatio < 1);
document.querySelector(".hide-stuff-arrow").classList.add("user-scrolled-down", e.intersectionRatio < 1);
},
{ threshold: [1] }
);
The return of the callback is meaningless to the intersection observer so this should not affect the existing behavior.
Also see: how arrow functions differ from normal ones
Upvotes: 1