Forum Moderators: open
How can I set the first link set to active on page load? Setting the class="active" will not help as when I click another button the link still has the active class.
Any help will be much appreciated.
-------- javascript -------
<script type="text/javascript" charset="utf-8">
var currlink = null;
function toggleactive(elm)
{
if(currlink)
currlink.className = currlink.className.replace(/\bactive\b/,'');
currlink = elm;
currlink.className += " active";
}
</script>
-------- html -------
<ul id="buttons">
<li id="but_intro"><a id="link1" href="#" name="link1" onclick="toggleactive(this);return false;"></a></li>
<li id="but_flexible"><a id="link2" href="#" name="link2" onclick="toggleactive(this);return false;"></a></li>
<li id="but_support"><a id="link3" href="#" name="link3" onclick="toggleactive(this);return false;"></a></li>
<li id="but_pro"><a id="link4" href="#" name="link4" onclick="toggleactive(this);return false;"></a></li>
<li id="but_w3c"><a id="link5" href="#" name="link5" onclick="toggleactive(this);return false;"></a></li>
</ul>
@ penders: setting the class="active" on link1 and modifying var currlink as you suggested, unfortunately, doesn't work. Clicking another link, the link1 stays activated.
@ Fotiman: there is any way you could provide a code example? Sorry but I have no experience at all with js.
Again, many thanks!
Perhaps on page load just call a script that searches for the link that has the className active and set it to currlink.
Well, if you don't mind using a JavaScript framework, you could use the Yahoo UI Library's DOM and Event Utilities. In which case, it would be something like this:
<!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">
<style type="text/css">
.active { font-weight: 700; }
</style>
<title></title>
<script type="text/javascript" src="http://yui.yahooapis.com/2.2.2/build/yahoo-dom-event/yahoo-dom-event.js"></script>
<script type="text/javascript" charset="utf-8">
YAHOO.util.Event.on(window, 'load', function(){
var currlink = YAHOO.util.Dom.getElementsByClassName('active', 'a', 'buttons');
// Attach behaviors
YAHOO.util.Event.on( YAHOO.util.Dom.getElementsBy(function(el){return true;}, 'a', 'buttons'), 'click', function(e) {
YAHOO.util.Event.stopEvent(e);
if(currlink) {
YAHOO.util.Dom.replaceClass(currlink, 'active', '');
}
currlink = this;
YAHOO.util.Dom.addClass(currlink, 'active');
});
});
</script>
</head>
<body>
<ul id="buttons">
<li id="but_intro"><a id="link1" href="#" name="link1">link1</a></li>
<li id="but_flexible"><a id="link2" href="#" name="link2">link2</a></li>
<li id="but_support"><a id="link3" href="#" name="link3">link3</a></li>
<li id="but_pro"><a id="link4" href="#" name="link4">link4</a></li>
<li id="but_w3c"><a id="link5" href="#" name="link5">link5</a></li>
</ul>
</body>
</html>
[edited by: Fotiman at 3:41 pm (utc) on June 18, 2007]