Tab style nav bar with Jquery
Question
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>
$(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");
});
});
<div id="nav">
<a>One</a>
<a>Tw0</a>
<a>Three</a>
</div>
OTHER TIPS
Try CSS instead. Here's an article regarding the Sliding Doors technique:
http://www.alistapart.com/articles/slidingdoors/
EDIT Here's how you could apply click state (assuming your HTML is valid):
$(".yourLink").cick(function() {
$(".yourLink").removeClass("selected");
$(this).addClass("selected");
});
And just make sure you define the "selected" class in your CSS.
In conjuction with using background images + CSS for the tabs' appearance (as mentioned above), I suggest you denote your different link states using classes and then adjust your CSS from there. E.g.:
<div id="nav">
<a class="on" href="#">Link 1</a>
<a href="#">Link 1</a>
<a href="#">Link 1</a>
<a href="#">Link 1</a>
<a href="#">Link 1</a>
</div>
<style type="text/css">
#nav a { color: blue; }
#nav a.on { color: red; }
#nav a.current { color: green; }
</style>
<script type="text/javascript">
$(document).ready(function(){
$('#nav a').hover(
function(){ $(this).addClass('on'); },
function(){ $(this).removeClass('on'); }
);
});
</script>
Etc.