So normally when I visit for ex "index.html" and I give my a href link in my navbar the class "active" or whatever class and colour it so it defines which page I'm on
so
<a href="index.html" class="active">
and
a.active {
background-color: #009879;
color: white;
}
would just do the trick and highlights the page I'm currently on in the navbar
but I have a section in my index.html which I can go to by clicking on this in the navbar
<a href="index.html#about">
but if I trigger the class="active" for this section, then both the index and the section will be highlighted in my navbar
how do I make it so that when I'm on the section, my index.html loses its class=active and for the section to gain that class?
possibly if this could be done using only CSS!
TL;DR I need a way in CSS/JS that adds/removes the class for whatever element(s) I want it to be on.
Hi, The function you want in your project is called scrollspy and it is achieved with javascript. You can use the bootstrap or create the function in pure javascript. But in order not to reinvent the wheel I show you an example based on a vanilla javascript script from: https://github.com/cferdinandi/gumshoe.
var spy = new Gumshoe('#my-awesome-nav a');
html {
overflow-y: auto;
scroll-behavior: smooth;
}
/* Sets body width */
.container {
max-width: 90em;
width: 88%;
margin-left: auto;
margin-right: auto;
}
/**
* Grid
*/
.grid {
display: grid;
grid-gap: 2em;
grid-template-columns: 30% 70%;
}
#my-awesome-nav {
position: fixed;
}
#my-awesome-nav li.active {
background-color: black;
}
#my-awesome-nav li.active a {
color: white;
}
/**
* Sections
*/
.section {
color: #ffffff;
height: 95vh;
margin: 0;
padding: 2em;
}
#eenie {
background-color: #0088cc;
}
#meenie {
background-color: rebeccapurple;
}
#miney {
background-color: #272727;
}
#mo {
background-color: #f42b37;
}
<script src="https://cdn.jsdelivr.net/gh/cferdinandi/gumshoe/dist/gumshoe.polyfills.min.js"></script>
<div class="container">
<div class="grid">
<nav>
<ul id="my-awesome-nav">
<li><a href="#eenie">Eenie</a></li>
<li><a href="#meenie">Meenie</a></li>
<li><a href="#miney">Miney</a></li>
<li><a href="#mo">Mo</a></li>
</ul>
</nav>
<main>
<div class="section" id="eenie">
Eenie...
</div>
<div class="section" id="meenie">
Meenie...
</div>
<div class="section" id="miney">
Miney...
</div>
<div class="section" id="mo">
Mo...
</div>
<p><a data-scroll href="#top">Back to the top</a></p>
</main>
</div>
</div>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With