I have a link that brings the user to the Italian version of my website. I want to define the href attribute of this anchor using javascript so that it is relative to the current page. Here is the html:
<a href="javascript:changeLanguage()" id="lang-link"" >Italiano</a>
and here is the javascript:
function changeLanguage(){
var pathArray = window.location.pathname.split( '/' );
var filename = pathArray[2];
var newURL = window.location.protocol + "://" + window.location.host + "/ITALIANO/" + filename;
document.getElementById("lang-link").href= newURL;
};
When I click on the link, I have to click twice to load the new page and it loads an error. My coding brings me to:
http://www.ilcataldo.com/de/http:://www.ilcataldo.com/ITALIANO/shows.html
instead of:
http://www.ilcataldo.com/ITALIANO/shows.html
Can someone please explain what I'm doing wrong? I am a self-taught novice!
Thanks,
Cathal
Change this:
var newURL = window.location.protocol + "://" + window.location.host + "/ITALIANO/" + filename;
document.getElementById("lang-link").href= newURL;
to this:
window.location = window.location.protocol + "//" + window.location.host + "/ITALIANO/" + filename;
The reason you're seeing a bad URL has to do with the construction of the URL in your code. You were inserting an extraneous :
in the protocol prefix, which is not the proper URI format. Consequently, the browser assumed the link reference was relative to the current document.
The reason you had to click twice to reload the page is because your code was only modifying the link href
on the first click. It was not instructing the browser to load the new page.