Search code examples
jqueryrollover

Tab style nav bar with Jquery


Hi I have been trying to find an answer to this question. I am trying to create a nav bar using jquery that uses rollovers. So there is an On state, off state, clicked state for three diffrent tabs/images.

example: Home | Support | About

The problme i'm having is getting the clicked/on state to turn off the other image/tab if it was already on/clicked state. What keeps hapening is each tab stays active when clicked instead of toggling off and on.

Here is the code

$(document).ready(function() {


    // Navigation rollovers
    $("#nav a").mouseover(function(){
        imgsrc = $(this).children("img").attr("src");
        matches = imgsrc.match(/_on/);

        // don't do the rollover if state is already ON
        if (!matches) {
        imgsrcON = imgsrc.replace(/_off.gif$/ig,"_on.gif"); // strip off extension
        $(this).children("img").attr("src", imgsrcON);
        }

    });

        $("#nav a").click(function(){
        imgsrc = $(this).children("img").attr("src");
        matchesclk = imgsrc.match(/_clk/);


        if (!matchesclk) {
        imgsrcClkON = imgsrc.replace(/_on.gif$/ig,"_clk.gif"); // strip off extension
        $(this).children("img").attr("src", imgsrcClkON);
        }

    }); 

    $("#nav a").mouseout(function(){
        $(this).children("img").attr("src", imgsrc);
    });


}); 

Any help would be appreciated. I am new to jquery and I am really having a touch time with this.


Solution

  • Will this work for you?

    <style>
        .click {
            background-image: url(images/click.png);
        }
    
        .over {
            background-image: url(images/over.png);
        }
    </style>
    
    <script>
        $(document).ready(function () {
            $("#nav a").mouseover(function () {
                if ($(this).attr("class") != "click")
                    $(this).addClass("over");
            });
    
            $("#nav a").click(function () {
                $("#nav a.click").removeClass("click");
                $(this).addClass("click");
            });
    
            $("#nav a").mouseout(function () {
                $(this).removeClass("over");
            });
        });
    </script>
    
    <div id="nav">
        <a>One</a>
        <a>Tw0</a>
        <a>Three</a>
    </div>