Home > Blockchain >  Click a button with part of current URL for language use
Click a button with part of current URL for language use

Time:07-13

Halo everyone,

Cause I got a website which have many language and each language will have a subdirectory.

for example

1) sample.com/en
2) sample.com/jp
3) sample.com/zh

And the question is, I want the user stay on their curent page, when they change the language.

for example
sample.com/en/about-us (change to) 
sample.com/jp/about-us

I have all the button for each language. Just want to use javascript to make each button will go to their own language with their current URL.

When I am in one language "about us" page, other language button link will turn to something like this.

US button > sample.com/en/about-us(base on current URL.)
Japan button> sample.com/jp/about-us (just change the country code with every other botton)

<input type="button" onclick="location.href=window.location.href.replace('en', 'el');" value="Greek" />

I found something like this, but with no luck.

Thanks everyone!!!!

CodePudding user response:

To clean up the HTML, you can add a data attribute to each button for that button's language.

Then instead of using an inline event handler, you can delegate the event handler to the document itself. Then check for a data attribute for language. Then I'm splitting the current URL by the slash to get the page name. In my example, I'm logging the URL but you will want to location.href the URL instead.

var currentLocation = location.href.split("/");
let _page = currentLocation[currentLocation.length-1];

document.addEventListener("click",function(e){
  let btn = e.target;
  if(btn.getAttribute("data-lang")){
     _url = "/"   btn.getAttribute("data-lang")   "/"   _page;
     console.log(_url)
     //location.href = _url
  }
});
<button data-lang="en">En</button>
<button data-lang="es">Es</button>

CodePudding user response:

to redirect to another language, use the following code

<input type="button" onclick="window.location.href = window.location.href.replace('sample.com/en', 'sample.com/jp');" value="Greek" />
  • Related