Dave Elliott

Navigation

Skip navigation.

Search

Site navigation

Email conversation

FromDave Elliott
ToMe
Subjectquestion - how to change style based on location.hash?
Date4 August 2004 00:05
You site is a great reference for JavaScript, but the way.

What I have is a left nav list of links that stays in the same position on
all pages throughout my site.  When a user clicks on a link in the list, he
is taken to the respective page, and the nav list (on that page) shows the
link which was clicked (in the previous page) in a different color so he
knows where he is in the nav list.  But sometimes the links in the nav list
point to different named anchors on the same page.  So I need to test for a
given named anchor when that page loads and change the link’s color if the
test is true.  Being new to JavaScript, I could only come up with this
pseudo code:

I code the link like this:

<p><span id="currentlink">
  <a href="techpage.php#tech02" onClick="anchorname('#tech02')">Tech02</a>
</span></p>

Which calls this function:

function anchorname(n) {
var a=(window.location.hash);
if n=a {
  changeproperty span(currentlink).color=#CC0000;}
}

I’m not sure I should use the css id #currentlink as that has a (related,
but) different purpose.  I think I’m on the right track with testing
location.hash, but not sure about how to apply changes to the style in the
span.

I am currently using only #currentlink (without JavaScript) in my site
http://xxx.xxxxxxxxxxxxxxxxx.xxx
Which does not handle named anchors in the nav list.  But this may give you
an idea of what I’m trying to do.

Any help is appreciated.

Thanks,
de
FromMe
ToDave Elliott
SubjectRe: question - how to change style based on location.hash?
Date4 August 2004 20:32
Dave,

this sounds so easy doesn't it? but there is a snag. what if one link on
the page is already highlighted? should it remove that highlight? and if
your PHP code has highlighted the default one but the javascript decides
that the hash actually points to another one?

function anchorname(n) {
if(!n) { return; }
for(var x = 0, y;y = document.links[x];x++) {
 if(!y.parentNode) { return; }
 if(y.hash==n) {
  y.parentNode.style.color = '#CC0000';
 } else if(y.parentNode.tagName.toLowerCase()=='span') {
  y.parentNode.style.color = '#000000';
 }
}
}
window.onload = function () { anchorname(location.hash); }
...
<p><span><a href="techpage.php#tech02"
onClick="anchorname('#tech02')">Tech02</a></span></p>

This is really just an attempt to understand what you want. I can make no
promises.

Mark 'Tarquin' Wilton-Jones - author of http://www.howtocreate.co.uk/
This site was created by Mark "Tarquin" Wilton-Jones.
Don't click this link unless you want to be banned from our site.