Search code examples
javascripteventsshow-hidesections

Show/Hide Content


I need to create a script in which will hide all content but one section in which is selected for my JavaScript class. function in which listens for a click event to a specific HTML section. Once this event has been triggered I need to show the section in which was clicked while having the other sections hidden. I think I have coded the EventListener's and the hide function properly! However, I think where I'm running into these issues is with my function. Sadly, this has to be done all in JavaScript (with HTML and some CSS). We need to have a navigation bar and have querySelectors along with event.targets.

Here's what I have so far:

Set object references

link1 = document.getElementById("program");
link2 = document.getElementById("history");
link3 = document.getElementById("efficiency");
link4 = document.getElementById("brains");

Add event listener

addEventListener("click", clicked);
link1.addEventListener("click", clicked);
link2.addEventListener("click", clicked);
link3.addEventListener("click", clicked);
link4.addEventListener("click", clicked);

Shows Content

function clicked(event){

    for (var i = 0; i<sections.length; i++){
        sections[i].className = "hidden"; //Looks at all the sections then changes/adds all the class names to "hidden"
    }

    event.target.href;
    event.target.className = "";

    //event.target.hash.className = "show";

    console.log(event.target.hash); //Logs tha function works and which link has been clicked
}

I was wondering if I could get some help?!

My full code is on JSFiddle!

Thanks!

UPDATE: I have narrowed down my question!


Solution

  • First, we need some way to link the titles to their sections. I have done this by adding data attributes to the navbar links:

    <nav>
        <a href="#program" data-section="program">Programming</a>
        <a href="#history" data-section="history">History</a>
        <a href="#efficiency" data-section="efficiency">Efficiency</a>
        <a href="#brains" data-section="brains">Brains</a>
    </nav>
    

    As you can see, the data-section attribute is the exact ID of the section we want to open.

    Then, we need to be able to get the section for a given data-section attribute:

    function getSection(name) {
        // find the section element with ID matching the name
        return document.querySelector("section#" + name);
    }
    

    Then, in our clicked event, we need to:

    1. Get the data-section information from the clicked element
    2. Get the element for the section
    3. Add the class show to the section element

    We can do this like so:

    var name = event.target.dataset.section;
    var section = getSection(name);
    section.className = "show";
    

    I've stored my changes on JSFiddle so you can see.