ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

JS Tutorial version 2: Developing a simple tabbed panel using jQuery

Updated on January 20, 2013

I'm writing another article on this great platform after a 1+ year long break. I was very busy in my day job and many other things which stopped me from writing more tutorial on web development. I'm re-initializing here again with this article focusing on "How to create a simple tabbed panel using jQuery (A JavaScript library)". This article is being published on the request of "Marcos" of upgrading my previous article. I could edit the previous one instead of creating a new one but I think I should not because code in my previous version of this article was not meant to be used in productive works. It was just been published for learning purposes. It is still doing its task of teaching newbies (students and freelancers) in this field of development.

So, here we go. I did many modifications in the code of my previous article to build up a new version. The only thing that has been replaced completely is the JS code with jQuery methodology of writing JS code. This time we are using the jQuery library as it makes the work of JavaScript developers faster and easier. jQuery's tag line "Write less, Do more" is 100% stands on its point.

In the beginning, jQuery would be very complex to you (As per my own experience) but as you grow, You'll definitely get addicted to it. jQuery is the mostly used JS library in the commercial web development works. You can find a big list of tutorials published on web to start learning. The only final thing I can say is, jQuery the best thing I have ever found, Without it my career growth rate would be like that of tortoise speed.



Problem in previous version of this article

The problem detected in previous version of code by marcos is that, "There cant be any two instances of tabbed panel run on the same web page". It has been two years now since article was first published and no one raised this requirement till now.

jQuery code of tabbed panel

        <!--//Loading the jQuery library from GOOGLE SERVERS (CDN: Content Delivery Network)-->
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <!--Writing the tabbed panel javascript code-->
        <script type="text/javascript">
            //When current document ready fore performing JS/jQuery operations
            $(document).ready(function(){
                
                //On Clicking the menu item of Tabbed Panel
                $('.lh').click(function(){
                    
                    //PARENT and CHILDREN methods of jQuery are used 
                    //to keep the uniqueness of multiple tabbed panel on same page
                    
                    //Finiding the root tag of current tab panel on which click action performed
                    //(Main Div tag (tabbed panel) under which currently clicked menu element exists)
                    var parent_tabbed_section = $(this).parent('ul').parent('div').parent('.tabbed_section');
                    
                    //Finding the position of cliked menu in all menus of current tab
                    //First, Going to parent element
                    //Then, In all menus exist inside parent element
                    //Finding the numerical position (index) of clicked menu
                    var indexOf = $(this).parent('ul').children('.lh').index(this);
                    
                    //First, Setting all the menus to their default "GRAY" color
                    $(this).parent('ul').children('.lh').css('background-color','gray');
                    
                    //Now, Changing the color of current one to silver
                    $(this).css('background-color','#eeeeee');
                    
                    //Retrieving the content to be displayed inside content panel of current tabbed panel
                    //Storing it in JS variable named html_to_show
                    var html_to_show = $(parent_tabbed_section).children('.content_tab:eq('+ indexOf +')').html();
                    
                    //Displaying the content in tabbed panel
                    $(parent_tabbed_section).children('.Display_content').html(html_to_show);
                });
                
                //By default seeting the first menu of each tabbed block as clicked
                //So, content relative to it can be displayed
                $('.tabbed_section div ul').each(function(){
                    $(this).children('.lh:first').trigger('click');
                });
            })
        </script>

You can see the jQuery code above. You need to paste this code in head tags, No need of customization. Just for you ease in understanding the concept behind tabbed panel, I documented the code properly. You can see the green lines (Documentation) and blue lines (Actual jQuery code).

Now, You can see below the CSS code. This code is also need to be placed in head tags. I did not modified anything in CSS except replacing '#' with '.' characters before class names. We are not using IDs anymore in our html code because IDs cant be used more than one time in single web page.

CSS (Cascading stylesheet) Code

<style type="text/css">
            div.content_tab {
                display:none;
            }
            .tabbed_section {
                border: 2px solid gray;
                width: 300px; /* width of tabbed panel */
            }
            .menu {
                clear: both;
                width: 300px;
            }
            .Display_content {
                clear: both;
                min-height: 44px;
                padding: 2px;
                border: 1px solid gray;
            }
            .ul_tabs {
                clear: both;
                padding: 0px;
                margin: 0px;
            }
            .lh {
                padding:5px;
                background-color: gray;
                list-style: none;
                width: 88px;
                height: 25px;
                float: left;
                border: 1px solid #FFFFFA;
                text-align:center;
            }
            li.lh:hover {
                background-color: white;
                cursor: pointer;
            }

        </style>

If you know the syntax of any programming language, then, It'll not be difficult for you to understand. This statement applies to CSS and HTML codes too. JavaScript itself is programming language but it runs only in browsers as long as not supported by other tools :).

Below is our HTML code. I removed all the IDs from HTML tags which were in previous version. This time we are not using them because there will be multiple instances of tabbed panel running on same page and they will create problems. You can see, there are three different parent DIV's whose class name are "tabbed_section". They are three but code inside each of them is exactly same. You can create as many copies of it on same web page. Structure of code could be easily understood as it is properly formatted by editor I use.

        <div class="tabbed_section">
            <div class="menu">
                <ul class="ul_tabs">
                    <li class="lh">
                        Head1
                    </li>
                    <li class="lh">
                        Head2
                    </li>
                    <li class="lh">
                        Head3
                    </li>
                </ul>
            </div>
            <div class="Display_content"></div>
            <div class="content_tab">
                content in tab1111
            </div>
            <div class="content_tab">
                content in tab2222
            </div>
            <div class="content_tab">
                content in tab3333
            </div>
        </div>
        <hr/>
        <div class="tabbed_section">
            <div class="menu">
                <ul class="ul_tabs">
                    <li class="lh">
                        Head1
                    </li>
                    <li class="lh">
                        Head2
                    </li>
                    <li class="lh">
                        Head3
                    </li>
                </ul>
            </div>
            <div class="Display_content"></div>
            <div class="content_tab">
                content in tab1111
            </div>
            <div class="content_tab">
                content in tab2222
            </div>
            <div class="content_tab">
                content in tab3333
            </div>
        </div>
        <hr/>
        <div class="tabbed_section">
            <div class="menu">
                <ul class="ul_tabs">
                    <li class="lh">
                        Head1
                    </li>
                    <li class="lh">
                        Head2
                    </li>
                    <li class="lh">
                        Head3
                    </li>
                </ul>
            </div>
            <div class="Display_content"></div>
            <div class="content_tab">
                content in tab1111
            </div>
            <div class="content_tab">
                content in tab2222
            </div>
            <div class="content_tab">
                content in tab3333
            </div>
        </div>
    

Snapshot of tabbed panel

Snapshot of tabbed panel created using jQuery.
Snapshot of tabbed panel created using jQuery. | Source

What are your thoughts about the article?

See results

So, that was all that I did to create new version of my article. I hope It'd be easier to use.

Regards,

Sam

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      Al Rios 

      4 years ago

      Line four in your javascript is coming up as error in code?

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: https://hubpages.com/privacy-policy#gdpr

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)