Search code examples
jquerycssasp.netwebformsmaster-pages

How to highlight selected tab in Web Forms including Master Page


I know without a master page it is as simple as setting the tab for each page to selected but how do I do this with master page?

Home Page

enter image description here

Houses Page (The home tab stays selected even though its on the houses page)

enter image description here

Expected Output

enter image description here

I used the following tutorial Highlighting the selected jquery tab using asp.net Master page

Master Page

<script type = "text/javascript">
        $(function () {
            $('#scrollToTop').bind("click", function () {
                $('html, body').animate({ scrollTop: 0 }, 1200);
                return false;
            });

            function setCurrentTab(selectedTab) {
                $('li').removeClass('selected');
                $('[id=selectedTab]').addClass('selected');
            }
        });
    </script>

<div id="navigation">
                    <ul>
                        <li id="tab1">
                            <a href="Home.aspx">Home</a>
                        </li>
                        <li id="tab2">
                            <a href="Houses.aspx">Houses</a>
                        </li>
                        <li id="tab3">
                            <a href="About.aspx">About</a>
                        </li>
                        <li id="tab4">
                            <a href="Contact.aspx">Contact</a>
                        </li>
                    </ul>
                </div>

Houses.aspx

<script>
        setCurrentTab('tab2');
    </script>

CSS

#navigation li, #navigation li a:hover, #navigation li.selected a {
    background-image: url(../images/bg-menu.png);
    background-repeat: repeat-x;

Solution

  • Replace this code

    $('[id=selectedTab]').addClass('selected');
    

    with

    $('[id='+selectedTab+']').addClass('selected'); 
    

    or with

    $('#'+selectedTab).addClass('selected');
    

    You have your selected tab id in selectedTab variable, but you are using it as literal, so concat this selectedTab with id.

    On Houses.aspx, call setCurrentTab function on document.ready. like

    $(function(){ setCurrentTab('tab2'); });