Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / HTML

Managing Multiple Views in Single Page HTML Apps

5.00/5 (1 vote)
4 Apr 2013CPOL1 min read 37K  
This article demonstrates how to manage multiple views in a single HTML page using jQuery.

Introduction

Many of you might have worked with Single Page HTML Apps which require many sections (I'll call it as View hereafter) to be hidden and shown appropriately. Though it is not the toughest task, it requires a lot of code to manage those views.

This tip demonstrates how you can easily make such apps with HTML and jQuery.

HTML Markup

Let us begin with simple HTML markup which contains a lot of views. Each <div> which you want to be a separate page or view is added as a CSS class called 'view'.

HTML
<!DOCTYPE html>
 
<html>
<head>
    <title>Demo</title>
    <script src="jquery-1.9.1.min.js"></script>
    <style>
        .hide
        {
            display: none;
        }
    </style> 
</head>
<body>
    <div id="lotOfPages">

    <div class="view" id="page1">
            <h1>Page 1</h1>
        </div>
        
    <div class="view hide" id="page2">
            <h1>Page 2</h1>
        </div>

    <div class="view hide" id="page3">
            <h1>Page 3</h1>
        </div>

    </div>

    <button id="showPage1Btn" data-launch-view="page1">Page 1</button>
    <button id="showPage2Btn" data-launch-view="page2">Page 2</button>
    <button id="showPage3Btn" data-launch-view="page3">Page 3</button>

</body>
</html>

This markup has three 'div's which we call as view. Each <div> is added the 'view' class. Then, we have three buttons to launch each page when clicked. [You can replace button with any HTML element as per your requirements]. These buttons are added a HTML5 data attribute called 'data-launch-view' with the value of ID of the page we wish to display.

Initially, <div> with ID page1 is displayed and other pages are hidden.

JavaScript

Now let us add a script to this page which is required to show and hide appropriate views.

JavaScript
$(document).ready(function (e) {

        function showView(viewName) {
            $('.view').hide();
    $('#' + viewName).show();
    }

        $('[data-launch-view]').click(function (e) {
            e.preventDefault();
            var viewName = $(this).attr('data-launch-view');
            showView(viewName);
        });

    });

showView() function displays the required view by hiding all other views.

The next function makes elements with 'data-launch-view' attribute to load the appropriate view. The value of 'data-launch-view' attribute must be ID of the page (<div>) to be shown.

Now when buttons are clicked, the given view is shown by hiding other views. You can add as many views as needed without writing an additional script.

Image 1

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)