Search code examples
javascriptjqueryhtmlcss

How can I how one div and hide multiple others with jQuery?


I am working on page load event, one DIV will be display:block and two others are set to display:none.

Once the user clicks a button to view one of the hidden DIV's the style will switch so the hidden DIV will then be set to display:block and the other will be display: none.

I have this working currently, but I was looking to see if there was a more efficient way of approaching this.

Working Fiddle:

New fiddle...:

Any suggestions would be appreciated!


Solution

    1. Add Common Class to all the tab headers
    2. Add data-target attribute to show the element when clicked on tab-header
    3. Group all the tab-contents inside on container

    See the changes highlighted in HTML and inline comments in Javascript.

    Html:

    <div class="pageTabs">
        <div class="tabs">
            <span id="overview-btn" class="active tabHeader" data-target="#overview-section">Overview</span>
            //                                    ^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            <span id="itinerary-btn" class="tabHeader" data-target="#itinerary-section">Full Itinerary</span>
            //                       ^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            <span id="map-btn" class="tabHeader" data-target="#map-section">Map</span>
            //                 ^^^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^
        </div>
    </div>
    <div class="content">
        <div class="overview" id="overview-section">
            <p>Intro 1</p>
            <p>Intro 2</p>
            <p>Intro 3</p>
        </div>
        <div class="itinerary" id="itinerary-section">
            <div class="heading">Day 1</div>
            <p>blah blah blah</p>
            <hr>
            <div class="heading">Day 2</div>
            <p>blah blah blah</p>
            <hr>
            <div class="heading">Day 3</div>
            <p>blah blah blah</p>
            <hr>
            <div class="heading">Day 4</div>
            <p>blah blah blah</p>
            <hr>
            <div class="heading">Day 5</div>
            <p>blah blah blah</p>
            <hr>
        </div>
        <div class="map" id="map-section">map here...</div>
    </div>
    

    Javascript:

    $(document).ready(function () {
        // When tab-header is clicked
        $('.tabHeader').on('click', function () {
    
            // Add active class to the clicked element, and remove from other tab-headings
            $(this).addClass('active').siblings().removeClass('active');
    
            // Get the target element show it and hide other tab-contents
            $($(this).data('target')).show().siblings().hide();
        });
    });
    

    Demo: https://jsfiddle.net/tusharj/p9bnq8dp/2/