Forum Moderators: open
Denmark, Norway, Sweden When I click on 'Denmark', I would like the div with the id 'denmark' to appear, and the divs 'norway' and 'sweden' to disappear. This has to be possible, and finding a solution is driving me nuts! Any help or pointers anyone could give would be useful.
function groupSelector(el, elList) {
var i, numItems = elList.length;
// Hide all items in the list
for (i = 0; i < numItems; i++) {
elList[i].style.display = 'none';
}
// Show the one item
if (el != null) {
el.style.display = 'block';
}
}
In that example, I'm explicitly setting the display property of the style attribute. A better solution might be to add/remove a class. Using the YUI it would be something like
YAHOO.util.Dom.replaceClass(el,'shown','hidden');
Now you'd need an array of all the elements you want hidden:
var countries = [
document.getElementById('Denmark'),
document.getElementById('Sweden'),
document.getElementById('Norway')
];
And you'll need to attach your event handler to your links. Here is a working example that ties it all together:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" >
<title>Untitled</title>
</head>
<body>
<div>
<ul id="countryLinks">
<li><a href="#Denmark">Denmark</a></li>
<li><a href="#Sweden">Sweden</a></li>
<li><a href="#Norway">Norway</a></li>
</ul>
<div id="Denmark">Welcome to Denmark!</div>
<div id="Sweden">I am Inga from Sweden!</div>
<div id="Norway">Norway! Way!</div>
</div>
<script type="text/javascript">
window.onload = function () {
var countries = [
document.getElementById('Denmark'),
document.getElementById('Sweden'),
document.getElementById('Norway')
];
var i, countryLinks = document.getElementById('countryLinks');
function groupSelector(el, elList) {
var i, numItems = elList.length;
// Hide all items in the list
for (i = 0; i < numItems; i++) {
elList[i].style.display = 'none';
}
// Show the one item
if (el != null) {
el.style.display = 'block';
}
}
// Attach handler to links
var cLinks = countryLinks.getElementsByTagName('a');
for (i = 0; i < cLinks.length; i++) {
cLinks[i].onclick = function (el, elList) {
return function () {
groupSelector(el, elList);
return false;
};
}(document.getElementById(cLinks[i].href.substr(cLinks[i].href.indexOf('#')+1)), countries);
}
};
</script>
</body>
</html>
Note, this example is not doing a whole lot of error checking, so use with caution.
This bit of code:
(document.getElementById(cLinks[i].href.substr(cLinks[i].href.indexOf('#')+1)), countries)
Hope this helps.
groupSelector(countries[0], countries);
[edited by: Fotiman at 3:20 pm (utc) on Oct. 29, 2008]