Today I was doing some works on java script and html to make a inline virtual keyboard. But I was searching google for a script that can change the link text that means anchor tag’s text dynamically. Opps..I took more that 2 hour to solve it and make it cross browser compatible. So here I want to share the code that I used in my works and the links that helps me.
Suppose you want make something for each click in a link it’s text will be toggled.
like:
<a href=”url here”>Show</a>
<a href=”url here”>Hide</a>
<a href=”url here”>Show</a>
<a href=”url here”>hide</a> ….
Let’s here is the code :
<a href=”#” onclick=”showhide();” id=”linkid”>Show</a>
<script language=”javascript”>
var link = document.getElementById(‘linkid’);
function showhide()
{
if (document.all)
{ //IS IE 4 or 5 or later
if(link.innerText==’Show’)
{
link.innerText=’Hide’;
}
else
{
link.innerText=’Show’;
}
}
//IS NETSCAPE 4 or below
if (document.layers)
{
if(link.innerText==’Show’)
{
link.innerText=’Hide’;
}
else
{
link.innerText=’Show’;
}
//alert(“NETSCAPE 4 or below”);
}
//Mozilla/Netscape6+ and all the other Gecko-based browsers
if (document.getElementById &&!document.all)
{
if(link.firstChild.nodeValue==’Show’)
{
link.firstChild.nodeValue=’Hide’;
}
else
{
link.firstChild.nodeValue=’Show’;
}
//alert(link.firstChild.nodeValue);
//alert(” by id and not all”);
}
}
</script>
This code is compatible with most known browsers..:D
Another way:
function toggleshowhide()
{
var anchors = document.getElementsByTagName(“a”);
for(var i = 0; i < anchors.length; ++i)
{
if(anchors[i].firstChild.data == “Show”)
{
anchors[i].replaceChild(document.createTextNode(“Hide”),
anchors[i].firstChild);
}
else if(anchors[i].firstChild.data == “Hide”)
{
anchors[i].replaceChild(document.createTextNode(“Show”),
anchors[i].firstChild);
}
}
}