Cataldo
Cataldo

Reputation: 23

changing a link url with javascript

This is a javascript menu for a website I'm updating. I want to add a dynamic link (id=IT-LINK) to link to the Italian version of the site. But the URL needs to change depending on which page the viewer is on. Can someone please tell me how to do it!? I'm very new to javascript and am learning by myself. Thanks, Cataldo

window.onload = uline;

var pagename = document.getElementById("TAG").getAttribute("data-name");

function uline()
{
if (pagename == 'HOME' )
document.getElementById(pagename).style.color="#ffffff";
else
document.getElementById(pagename).style.textDecoration="underline";
}


document.write('<DIV CLASS=RIGHT><B>');

document.write('<a href=\"+link+'\"     id=IT-LINK      >ITALIANO</a>    &nbsp;&nbsp;&nbsp;');
document.write('<br><br>');
document.write('<a href="news.html"     id=NEWSLETTER   >NEWSLETTER</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="prodotti.html" id=PRODUCTS     >PRODUCTS</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="bio.html"      id=BIO          >PHILOSOPHY/BIOG</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="contatti.html" id=CONTACTS     >CONTACTS</a> &nbsp;&nbsp;&nbsp;');
document.write('<a href="home.html"     id=HOME         >HOME</a>');

document.write('</B></DIV>');

Upvotes: 0

Views: 649

Answers (3)

Cataldo
Cataldo

Reputation: 23

Thanks guys for your help, but I found an easier way of doing it. By adding "/it" to the URL I get a link that brings me to the Italian version of the current web page.

document.write('<font size=2.5><a href="it/home.html"   id=IT-LINK      >ITALIANO</a></font> &nbsp;&nbsp;&nbsp;');

var newURL = window.location.protocol + "//" + window.location.host + "/it" + window.location.pathname;
document.getElementById("IT-LINK").href = newURL;

BUT! Now I must ask your help in doing the opposite: How can I take out "/it" from the Italian URL to bring me back to the English version?

Upvotes: 0

S4beR
S4beR

Reputation: 1847

I dont really understand how you will find the page but i will leave that logic to you. To replace url you can use below javascript code.

//your logic to find page and corresponding url
    document.getElementById(linkId).setAttribute('href',yourLink);

Let me now if more information is required.

Upvotes: 1

Alytrem
Alytrem

Reputation: 2620

You should put your link in your HTML with a href to the italian home page. This will be the miniumum if your visitor has not javascript enabled. Then for those with javascript, you can do this :

document.getElementById("IT-LINK").href = getItalianVersionOf(window.location.href);

where getItalianVersionOf takes your page url and gives the italian version of this url.

Note that doing that on server side (with PHP for example) would be better.

Upvotes: 0

Related Questions