Skip to content
Advertisement

Setting up an .active class to a dynamically created link JS

I built a navbar a few weeks back and just realised I did not set an .active class on it. Now, I built the navbar and the links dynamically in JS and would now like to give whichever one is active the according CSS.

This is how I built the navbar in JS:

JavaScript

I have more than one link, but for this purpose I don’t need to show it all. So now the goal is to build a generic function that gives the active element within the navbar the according class.

JavaScript

And this is what my CSS looks like:

JavaScript

I am guessing there is something missing/not completely right in the second snippet of the JS code since nothing is happening when my link is active. I get the animation that I would like to get, but then it disappears once the user is redirected to that specific link, so you wouldn’t know which sub-page you are on.

Advertisement

Answer

this is wrong

JavaScript

“ele” is the <li>, you are adding the “active” class to the <ul> via the parentNode, might be better to use the “e” event from the click and use e.target and then try and set the active class on the <a> or use childNode/children to get at your <a>

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement