How to Toggle Between Page Sections

I have a navigation bar where the tab gets highlighted if it’s clicked on. I also want it to highlight the section of the page I’m on. The HTML for the page section looks like this:

<section id="section1" data-nav="Section 1" class="active">
<div class="landing__container">
<h2>Section 1</h2>
<p>Lorem ipsum </p>
</div>
</section>

Here is the javascript I’m using. It works to highlight the tab that I’m on but it doesn’t highlight the section.

var tabs = document.getElementsByTagName("li");

for (var i = 0; i < tabs.length; i++) {
tabs[i].addEventListener("click", function() {
var element = document.getElementsByTagName("section");
element.classList.toggle('active');
var current = document.getElementsByClassName("active");
current[0].className = current[0].className.replace("active", "");
this.className += "active";
});
}

Hi @makamo661 I’m assuming the “li” is the one currently being highlighted, as you have

var tabs = document.getElementsByTagName("li");

Can you show the the html for the tabs and the sections. You need a relationship between the tab selected and the section.

Is a section nested within the same tab or is the html for the sections separate.

You can’t use active for the section and the tab using the js you have above as you aren’t determining which is which.

If you are using classlist then use it for all the class name changes as its simpler.

1 Like

on a side/general note, i dislike the use of ‘active’ as a class name, as it’s already a selector in css.
.active and :active are just too close for me…shrug

Back to the main point, you’ll need to walk the dom backwards from this in order to find the section that the click corresponds to.

that tries to turn on every other section, and turn off the current active section. Probably not what you’re trying to do.

Generally when doing something like this, the flow is:
Remove the tag from everything.
Add the tag to the required element(s).

1 Like

When I add the following it doesn’t add the class. Doesn’t matter where in the code I am, it just doesn’t do it.

var section2 = document.getElementById(“section2”);
section2.classList.add(“active”);

My css was wrong. It’s working now.

It’s working now. I used the following:


var listelement1 = document.createElement('li');
listelement1.innerHTML = "TAB 1";
var section1 = document.getElementById("section1");

listelement1.addEventListener("click", function(){
document.location.href = '#section1';
section1.classList.add("my-active");
});
2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.