Friday, February 17, 2017

How to Create Tabs UI using HTML, CSS, jQuery, JSP and JavaScript

JSP is still a popular technology for developing view part of Struts and Spring based Java application, but unfortunately it doesn't have rich UI support available in GWT, or any other library. On other day, we had a requirement to display HTML tables inside tabs, basically we had two tables of different data set and we need to display them in their own tabs. User can navigate from one tab to other, and CSS should take care of which tab is currently selected, by highlighting active tab. Like many Java developers, our hands on HTML, CSS and JavaScript is little bit tight than a web guy, and since our application is not using any UI framework, we had to rely on JSP to do this job.

Since display tag is my favourite, I had no problem to dealing with tabular data, our only concern was how we will develop tabbed UI by just using HTML, CSS, JavaScript or may be jQuery. It looks everything is possible with these technology, we eventually able to develop our JSP page, which can show data in tabs.

So if you need to create tabs in JSP page, you can use this code sample, all you need to ensure is you have required libraries e.g. display tag library, JSTL core tag library and jQuery. I will explain you step by step how to create tabs in html or jsp page.

HTML, CSS, jQuery, JSP and JavaScript for TAB UI

Here is our JSP page to show tabbed ui using only html, CSS, jQuery and JavaScript. For simplicity reason I have combined everything in JSP page, but this is not exactly we have used it. We follow project guidelines and best practices and has separate files for CSS, HTML, and JavaScript.

Also writing Java code in JSP is not recommended, so avoid that part as well. You should write your Java code inside  model and controller classes. Your view class e.g. JSP page, should only render data created by model, believe a dumb JSP is the best JSP. If you scan through this JSP file, first part is importing Java classes e.g. ArrayList, List and a domain class Contact, next is importing tab libraries e.g. display tag and JSTL core tag library.

Since we are also displaying tabular data, for this sample purpose, I had  used dispalytag.css file, available in display tag examples, when you download display tag. Next is our custom CSS required for tabbed UI and then we have jQuery code, which does the magic of creating tabs and managing them i.e. keeping track of which tab is active and changing its CSS class to highlight it.

To create tabs in JSP page, we have used an unordered list <ul>   , which contains two list items for each tabs. This list item hyper link to two <div id='tab1'blocks, with id tab1 and tab2, which acts as container to hold tab data. Since we need to show HTML tables inside tabs, we have put  <display:table> inside these divs.

Magic of showing data only from active tab is done using CSS. Each container div has a CSS class class="tab_content" , which is just display:none, to make them invisible. When page loads, jQuery get hashtag from current URL to find out which tab is active, and subsequently assign it a class called active, and make it visible.

Same thing is done on the click as well. When use clicks one of the tab, jQuery first removes active class from previous tab and then assign it to new tab. It then hides the previous tab and show new tab by calling show() method. You can even use jQuery methods fadeIn() and fadeOut() instead of show() and hide() for better effects.

<%@page import="java.util.ArrayList"%>
<%@page import="com.web.revision.Contact"%>
<%@page import="java.util.List"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib prefix="display" uri="" %>
<%@ taglib prefix="c" uri="" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"

        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JQuery Tab Example</title>
        <link rel="stylesheet" href="css/displaytag.css" type="text/css">
        <link rel="stylesheet" href="css/screen.css" type="text/css">
        <link rel="stylesheet" href="css/site.css" type="text/css">

             {padding:0; margin:0;}

            html {
                padding:15px 15px 0;

            p, h3 {

            div {

            .tabss li {

            .tabss a {
                padding:5px 10px;

            .tabss a{
            .tab_content {
                display: none;

        <script src="">

         // Wait until the DOM has loaded before querying the document

            //Active tab selection after page load       
            // For each set of tabs, we want to keep track of
            // which tab is active and it's associated content
            var $active, $content, $links = $(this).find('a');
            // If the location.hash matches one of the links, use that as the active tab.
            // If no match is found, use the first link as the initial active tab.
            $active = $($links.filter('[href="'+location.hash+'"]')[0]
                      || $links[0]);
            $content = $($active.attr('href'));
         $("#tabs li").click(function() {
             // First remove class "active" from currently active tab
             $("#tabs li").removeClass('active');
             // Now add class "active" to the selected/clicked tab
             // Hide all tab content

             // Here we get the href value of the selected tab
             var selected_tab = $(this).find("a").attr("href");      

             var starting = selected_tab.indexOf("#");
             var sub = selected_tab.substring(starting);
             //write active tab into cookie
             // At the end, we add return false so that the click on the
            // link is not executed
             return false;



            List<Contact> cricketers = new ArrayList<Contact>();
            cricketers.add(new Contact("Kohli", 98273633, "Mohali"));
            cricketers.add(new Contact("Dhoni", 98273634, "Ranchi"));
            cricketers.add(new Contact("Sehwag", 98273635, "Delhi"));
            cricketers.add(new Contact("Rahane", 98273636, "Jaipur"));
            cricketers.add(new Contact("Gambhir", 98273637, "Delhi"));
            cricketers.add(new Contact("Rohit", 98273638, "Mumbai"));
            cricketers.add(new Contact("Dinda", 98273639, "Kolkata"));
            cricketers.add(new Contact("Ashwin", 98273640, "Chennai"));

            session.setAttribute("contacts", cricketers);
            List<Contact> actors = new ArrayList<Contact>();
            actors.add(new Contact("SRK", 98273633, "Mohali"));
            actors.add(new Contact("Salman", 98273634, "Ranchi"));
            actors.add(new Contact("Hrithik", 98273635, "Delhi"));
            actors.add(new Contact("Ajay", 98273636, "Jaipur"));
            actors.add(new Contact("Imran", 98273637, "Delhi"));
            actors.add(new Contact("John", 98273638, "Mumbai"));
            actors.add(new Contact("Akshay", 98273639, "Kolkata"));
            actors.add(new Contact("Sunil", 98273640, "Chennai"));
            session.setAttribute("actors", actors);


        <ul id='tabs' class="tabss">
            <li><a href='#tab1'>Tab 1</a></li>
            <li><a href='#tab2'>Tab 2</a></li>
        <div id='tab1' class="tab_content" >
            <h3>Section 1</h3>
            <p>This is First TAB </p>
            <display:table name="sessionScope.contacts"
                           requestURI="#tab1" pagesize="5"
                           export="true" sort="list" uid="one">
                <display:column property="name" title="Name"
                                sortable="true" headerClass="sortable" />
                <display:column property="contact" title="Contact"
                                sortable="true" headerClass="sortable" />
                <display:column property="city" title="City"
                                sortable="true" headerClass="sortable" />
        <div id='tab2' class="tab_content">
            <h3>Section 2</h3>
            <p>This is SECOND TAB</p>
            <display:table name="sessionScope.actors" requestURI="#tab2"      
                           pagesize="5" export="true" sort="list" uid="two">
                <display:column property="name" title="Name" sortable="true"     
                                headerClass="sortable" />
                <display:column property="contact" title="Contact" sortable="true"
                                headerClass="sortable" />
                <display:column property="city" title="City" sortable="true"
                                headerClass="sortable" />

This is how our tabbed UI  looks when displayed as HTML in client's browser. Active Tab is shown with pink, not a good choice but serves the purpose of highlight it. You can see contents of tab 1 has normal HTML code as well as table data generated from display tag. You can play with this table to understand display tag pagination and sorting as well.  Second image is for tab 2, you can see it contain different data i.e. first tab is about crickets and second tab is about Bollywood film stars.

Creating Tabbed UI using HTML, CSS, jQuery, JSP and JavaScript

    And this is how your second TAB will look like, when user will click on Tab 2 link

HTML, JSP, JQuery Tab UI example

That's all about How to create Tabs UI using HTML, CSS, jQuery and JSP in Java web application. If you like you can use any other library e.g. jQuery UI, which provides inbuilt tabs support, which will make your code more simpler than this. For example creating a tabbed page in jQuery UI will just require you to declare div elements for each tab and a list specifying all tabs, and then just calling  $( "#tabs" ).tabs();  method . jQuery UI will handle all JavaScript and CSS for you. Now it depends upon you, what you want :)

Further Reading
jQuery Fundamentals By Dan Wahlin
The Complete jQuery Course: From Beginner To Advanced!
Spring Framework 5: Beginner to Guru

Other jQuery and JavaScript tutorials you may like to explore
  • Top 5 jQuery Books Every Web Developer Should Read? (see here)
  • How to get current URL Parameter using jQuery? (solution)
  • How to use multiple jQuery Date picker element in one HTML page? (answer)
  • 10 Examples of jQuery selectors for Web Developers (tutorial)
  • How to redirect web page using jQuery code? (answer)
  • 3 Ways to parse HTML using JSoup in Java? (solution)
  • How to reload/refresh a page using jQuery? (answer)
  • How to prevent double submission of POST data using JavaScript? (solution)
  • How to modify multiple elements in one go in jQuery? (example)
  • How to check and uncheck checkboxes using jQuery? (tutorial)

No comments :

Post a Comment