faqts : Computers : Programming : Languages : JavaScript : Links

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

5 of 9 people (56%) answered Yes
Recently 5 of 9 people (56%) answered Yes

Entry

How can I change the text color of link dynamically which will work both in I.E and NN?

Jun 12th, 2002 07:19
David Blackledge, Jaishri Channe,


If you mean when the mouse hovers, look at this FAQ:
http://www.faqts.com/knowledge_base/view.phtml/aid/1619/fid/189
(scroll down for my shorter answer near the bottom)
If you mean "on a whim" then you'll want to make the link be in a layer 
in NN4, and re-write its inner document, or innerHTML in other browsers.  
However, re-writing the inner document doesn't work if you make it a 
relatively-positioned layer (this is a bug in NN4).  So, you have to use 
an absolutely positioned layer.  This isn't such a big deal (an 
absolutely positioned layer appears where it was defined unless you give 
it a top and/or left explicitly) except it now doesn't take up any flow 
space in the document.  So finally, you need to create an 
identically-sized layer that is relatively positioned (so it takes up 
the same space) but with visibility:hidden (so it doesn't show).
You end up with:
<span style="position:absolute" id="layer1"><a href="blah">my 
link</a></span><span style="position:relative;visibility:hidden"><a 
href="javascript:void(0)">my link</a></span>
Once you have this, you simply change the HTML contents of layer1 which 
is done with a minimum of fuss between browsers:
var newlink = '<A href="blah" style="color:red">my link</A>';
var lay = null;
if(document.getElementById)
 lay = document.getElementById("layer1");
else if(document.all)
 lay = document.all("layer1");
else if(document.layers)
 lay = document.layers["layer1"];
if(lay.innerHTML)
 lay.innerHTML = newlink;
else {
 lay.document.open();
 lay.document.writeln(newlink);
 lay.document.close();
}
Of course that would break on one of the lesser-used browsers if they 
don't support either innerHTML or a layer's inner document.  But that 
will work for all versions of IE and Netscape (4 and above)
David.
http://David.Blackledge.com