How Do Modify The Class Of The Inline Toc Element With Javascript?
Solution 1:
I've surrounded the content for each section with a paragraph
class, which is used for observing and also added a class to it's content content
- which is actually used nowhere yet, but I would still suggest to do that.
EDIT: integrated your idea how to select the element in case of multiple intersections.
https://jsbin.com/cufeyoreno/edit?js,output
let observer = newIntersectionObserver(handler, {
threshold: [0.2]
});
let selection;
let paragraphs = [...document.querySelectorAll("#main .paragraph")];
let submenu = [...document.querySelectorAll("ul.section-nav a")];
let paragraphMenuMap = paragraphs.reduce((acc, p) => {
let id = p.firstElementChild.id;
acc[id] = submenu.find(a => a.getAttribute("href") === "#" + id);
return acc;
}, {})
paragraphs.forEach(elem => observer.observe(elem));
functionhandler(entries) {
// Update selection with current entries.
selection = (selection || entries).map(
s => entries.find(e => e.target.firstElementChild.id === s.target.firstElementChild.id) || s
);
// Find last visible/intersecting (use a copied array for that, since reverse is an in place method)let lastVisibleId = [...selection].reverse().find(x => x.isIntersecting).target.firstElementChild.id;
for (s of selection) {
let targetId = s.target.firstElementChild.id;
// avoid searching the dom and just get the entry from our map.let a = paragraphMenuMap[targetId];
if (lastVisibleId === targetId) {
let parentElem = a;
// ensure that parent menu entries are selected toowhile (parentElem = parentElem.parentElement.closest(".toc-entry")) {
parentElem.classList.add("selected");
}
} else {
a.parentElement.classList.remove("selected");
}
}
};
Solution 2:
As I understood the answer you don't want to give it a style just add a class? If you would like to directly give some stylings to a li e.g. you could do this
document.getElementsByTagName("li").addEventListener("click",()=>{
this.style = "color:red";
})
but I guess you want to add already prepared classes in that case you need ClasList
document.getElementById("myDIV").classList.add("mystyle");
adds
document.getElementById("myDIV").classList.remove("mystyle");
removes
document.getElementById("myDIV").classList.toggle("mystyle");
toggles
in that case you need to add classes to them individually add ID's or same class to take each by class[0],class[1] etc... you need 2 things
`document.body.scrollTop;`
and for each height add class as shown above e.g.
if(document.body.scrollTop == 100px){
document.getElementById("myDIV").classList.add("mystyle");
}
and a better version if you want to remove from the previous
if(document.body.scrollTop == 100px){
for(let i = 0;i<classOfLis.length,i++){
classOfLis[i].classList.remove("selected");
}
document.getElementById("myDIV").classList.add("mystyle");
}
Post a Comment for "How Do Modify The Class Of The Inline Toc Element With Javascript?"