Create simple jQuery content switcher

When you have multiple articles on a single page that you do not want to display at the same time, you can create simple jQuery content switcher to help handle the situation. This can be done by stacking and displaying the content DIV’s one at a time with a little CSS, jQuery hide() and show() methods. Okay, let us learn how this can be achieved:

  1. Copy or replicate the HTML code below
    <ul class="content-link">
    <li><a href="#">Canada</a></li>
        <li><a href="#">United States</a></li>
                <li><a href="#">Germany</a></li>           
    </ul>
    
        <div id="content">
             <h2> Add title 1 here </h2>
               Add Content 1 here 
          </div><!-- End Cotent 1 -->
    
    <div id="content">
        <h2> Add title 2 here </h2>    
           Add Content 2 here
    </div><!-- End Cotent 2 -->
    
    <div id="content">
        <h2> Add title 3 here </h2>  
          Add Content 3 here
    </div><!-- End Cotent 3 -->
    
    

    Note: If we leave the above the way it is, everything will show at the same time. We need few lines of CSS code to help stack the content DIV’s properly and also display our choice of the content as the default.

  2. To stack the content DIV’s properly and also display our choice of the content as the default, replicate or copy the CSS codes below
    
    .content {
        width: 400px;
        height: 400px;
        position: absolute; /* Helps us stack the content on each other */
        margin: 0 0 0 200px;
       display: none; /* Hide all .content content */
    
    }
    
    .content:first-of-type { /* refers to the first content div */
        display: block; /* Shows the first content */
    }
    
    
  3. Now let’s create some jQuery functions to help display individual corresponding content DIV’s at the click of each of the Links provided. Add the list of functions below to your js file.
    
    $(function () {
        $('.content-link li').click(function () {     
            $('.content:visible').hide(); // Hides the content that is visible 
             $('.content').eq($(this).index()).show(); // show the corresponding content to the clicked Li */
    });
        });
    
    

See working and editable example here
If you have any questions please use the comment form below and I’d glad be to help.

Leave a Reply