...

View Full Version : nav selected state using JS



frickettz
06-26-2012, 08:05 AM
Hello all,

I'm trying to style a selected state for my nav links but I must be missing something.

Here's my html/css:

<div id="bar_under_brick">
<div class="container-970">
<div class="under_brick_links">
<a onclick="applySelectedTo(this);return false;" href="#" title="">Email Marketing</a>
<a onclick="applySelectedTo(this);return false;" class="selected" href="#" title="">Connect With Us</a>
<a onclick="applySelectedTo(this);return false;" href="#" title="">Ecommerce</a>
</div>
</div>
</div>

And here's the JavaScript I'm using for switching the class for selected state between these links when clicked:

<!-- apply selected state to drop down -->
<script type="text/javascript">
function applySelectedTo(link) {
var ul = document.getElementsByTagName("bar_under_brick")[0];
var allLinks = ul.getElementsByTagName("a");
for (var i=0; i<allLinks.length; i++) {
allLinks[i].className = "";
}
link.className = "selected";
}
</script>

The link that starts out with class="selected" on page load is working fine, but clicking the other links to switch that class does nothing. Am I missing something here?

vwphillips
06-26-2012, 10:21 AM
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">

<head>
<title></title>
<style type="text/css">
/*<![CDATA[*/

.selected {
color:red;
}

/*]]>*/
</style>

<script type="text/javascript">
/*<![CDATA[*/
function applySelectedTo(link) {
var ul = document.getElementsByTagName("DIV")[0]; // this will find the first DIV on the page
var ul = link.parentNode; // better
var allLinks = ul.getElementsByTagName("a");
for (var i=0; i<allLinks.length; i++) {
allLinks[i].className = "";
}
link.className = "selected";
}

/*]]>*/
</script></head>

<body>
<div id="bar_under_brick">
<div class="container-970">
<div class="under_brick_links">
<a onclick="applySelectedTo(this);return false;" href="#" title="">Email Marketing</a>
<a onclick="applySelectedTo(this);return false;" class="selected" href="#" title="">Connect With Us</a>
<a onclick="applySelectedTo(this);return false;" href="#" title="">Ecommerce</a>
</div>
</div>
</div>
</body>

</html>

frickettz
06-26-2012, 05:59 PM
Hm, well that worked, thanks a lot!

If I could trouble you (or anyone) a bit more - what does the CDATA part that you added do? I'd like to understand as much as I can about this.

I see that you wrapped it around the css styling as well as the JS script.

Thanks!
Matt



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum