I am trying to create a three tab menu where each tab toggles one of
three layers. The first span tab shows layer 1, hides layer 2/3, and
so on.
I am using javascript created by dreamweaver which seems over the top
and doesn't achieve what I want to anyway. I can toggle the layers but
I also want to toggle the background image of the selected tab.
If someone had an example of how to toggle through the layers and
change the background image of the corresponding tab I would be very
grateful.
Presumably your tabs are div elements. You can put an onclick
listener on each div (or on a div that encloses the tab divs) and sets
the background image of the clicked tab to the "selected" background
and the previously selected tab to the default (not selected)
background.
That is most easily achieved by adding and removing a class value,
then your page designers can play with the class rules to change the
look of the tabs and you don't have to change your script.
Here's a short example:
<head>
<title>Tabe example</title>
<style type="text/css">
#tabWrapper {
border: 1px solid red;
height: 52px;
}
.tab {
float: left;
border: 1px solid blue;
width: 100px;
height: 50px;
}
.selected {
background-color: #CCCC33;
}
</style>
<script type="text/javascript">
// Add a className
function addClass(el, className){
var re = new RegExp('(^|\\s)'+className+'(\\s|$)');
if (!re.test(el.className)) {
el.className += (' ' + className);
}
}
// Remove a className
function removeClass(el, className){
if (hasClassname(el, className)) {
var re = new RegExp('(^|\\s)'+className+'(\\s|$)');
el.className = (el.className.replace(re, ' '));
}
}
// See if el has className
function hasClassname(el, className){
var re = new RegExp('(^|\\s)'+className+'(\\s|$)');
return (re.test(el.className));
}
function setTab(e, wrapper) {
var el = e.target || e.srcElement;
var tabs = wrapper.childNodes;
var re = /^tab\d+/;
for (var i=0, iLen=tabs.length; i<iLen; i++) {
if (re.test(tabs
.id)) {
removeClass(tabs, 'selected');
}
}
addClass(el, ' selected');
}
</script>
</head>
<body>
<div id="tabWrapper" onclick="setTab(event, this);">
<div id="tab0" class="tab selected">Tab 0</div>
<div id="tab1" class="tab">Tab 1</div>
<div id="tab2" class="tab">Tab 2</div>
</div>
</body>