Change Language of Site With a HTML Button

Html two language option with button (without having to redirect to different page )

This is how i do it when i build a multi-lingual website. I put notes inside the code for clarification.

<form>
<label for="lang-switch">
<span lang="ko">언어</span>
<span lang="en">Language</span>
</label>
<select id="lang-switch">
<option value="en">English</option>
<option value="ko" selected>한국어</option>
</select>
</form>

<p>
<span lang="ko">한국어 텍스트</span>
<span lang="en">Text in English</span>
</p>

<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$('[lang]').hide(); // hide all lang attributes on start.
$('[lang="ko"]').show(); // show just Korean text (you can change it)
$('#lang-switch').change(function () { // put onchange event when user select option from select
var lang = $(this).val(); // decide which language to display using switch case. The rest is obvious (i think)
switch (lang) {
case 'en':
$('[lang]').hide();
$('[lang="en"]').show();
break;
case 'ko':
$('[lang]').hide();
$('[lang="ko"]').show();
break;
default:
$('[lang]').hide();
$('[lang="ko"]').show();
}
});
</script>

Hope it solve your problem.

(since i don't speak Korean i used google-translate for the example)

Change language of site with a html button

you can do this by

<a href="index.php?language=en">
<a href="index.php?language=no">

and get the languages and store them in cookie and include file according to cookie like

if ( !empty($_GET['language']) ) {
$_COOKIE['language'] = $_GET['language'] === 'en' ? 'en' : 'nl';
} else {
$_COOKIE['language'] = 'nl';
}
setcookie('language', $_COOKIE['language']);

and than

if ( $_COOKIE['language'] == "en") {
include("headerEn.php");
} else {
include("header.php");
} ?>

Change HTML Page Language

For a "pure JS" solution, in other words none of the usual solutions:

  • no Ajax to get the translated page text / replacement html
  • no redirect to a different page which can handle layout incongruities

one option is to store the translations on each div and switch them over using .text(). Do not code your translations into your javascript as that will quickly become impossible to maintain.

function switchLang(lang)
{
$("[data-" + lang + "]").text(function(i, e) {
return $(this).data(lang);
});
}

switchLang("en");

$(".switchlang").click(function() {
// change the button caption here, eg a flag
// UX opinion of whether it should be what it is
// or what it will become
// ie "de" click to make it "de"
// or "de" it's currently "de", click to change it
$(this).text($(this).data("lang"));

// switch to other language based on language on the button
var lang = $(this).data("lang") == "de" ? "en" : "de";
$(this).data("lang", lang);
switchLang(lang)
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<span data-de="Um die Nachrichten zu lesen"
data-en="To read the news"></span>, 
<span data-de="Übersetzungsdienst nicht verfügbar"
data-en="click here"></span>
<hr/>
<div data-en="no de translation for this line"></div>
<hr/>
<button class='switchlang' data-lang="en">de</button>

How to change a HTML page into a different language?

Level entry internationalization is achieved by using style properties:

function changeLanguage(languageCode) {
Array.from(document.getElementsByClassName('lang')).forEach(function (elem) {
if (elem.classList.contains('lang-' + languageCode)) {
elem.style.display = 'initial';
}
else {
elem.style.display = 'none';
}
});
}

// select handler
const selector = document.getElementById('langSelector');
selector.addEventListener('change', function (evt) {
changeLanguage(this.value);
});

// detect initial browser language
const lang = navigator.userLanguage || navigator.language || 'en-EN';
const startLang = Array.from(selector.options).map(opt => opt.value).find(val => lang.includes(val)) || 'en';
changeLanguage(startLang);

// updating select with start value
selector.selectedIndex = Array.from(selector.options).map(opt => opt.value).indexOf(startLang)

// fill "The selected language is:"
document.getElementById('browserLang').innerText = lang;
document.getElementById('startLang').innerText = startLang;
<div>
<p class="lang lang-en">My english text</p>
<p class="lang lang-de">Mein deutscher Text</p>
<p class="lang lang-it">Il mio testo</p>
<p class="lang lang-es">El mi texto</p>
<p class="lang lang-zh">我的文字</p>
</div>
<select id="langSelector">
<option value="en">English</option>
<option value="it">Italian</option>
<option value="es">Espanol</option>
<option value="de">Dutch</option>
<option value="zh">Chinese</option>
</select>
<div>
<p>Your browser language is: <b id="browserLang"></b></p>
<p>The selected language is: <b id="startLang"></b></p>
</div>

Change html language with a button and save after refreshing the page

There are few option, in my opinion best approach is to have different url for different language (domain.com, domain.com/pt, domain.com/fr) which is good for SEO.
You can also save language in cookie with javascript and then on page load fetch current language from cookie, check here how to set and fetch cookie.

how to switch language by toggle button?

I changed your code a bit. I putted an event listener on the input event of the checkbox and change the text content to the corresponding language based on the fact if the checkbox is checked or not.

The active class didn't do anything in your example so I removed that.

The currentTarget property of the event object will get you the element that the event handler is attached too. This is used to see if the checkbox is checked or not.

document.querySelector('#togBtn').addEventListener('input', (event) => {
document.querySelector('.title').textContent = data[event.currentTarget.checked ? 'japanese' : 'english'].title;
});

var data = {
"english": {
"title": "Hello World"
},
"japanese": {
"title": "ハロー・ワールド"
}
}
.switch {
position: relative;
display: inline-block;
width: 90px;
height: 34px;
}

.switch input {
display: none;
}

.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ca2222;
-webkit-transition: .4s;
transition: .4s;
}

.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}

input:checked+.slider {
background-color: #2ab934;
}

input:focus+.slider {
box-shadow: 0 0 1px #2196F3;
}

input:checked+.slider:before {
-webkit-transform: translateX(55px);
-ms-transform: translateX(55px);
transform: translateX(55px);
}


/*------ ADDED CSS ---------*/

.on {
display: none;
}

.on,
.off {
color: white;
position: absolute;
transform: translate(-50%, -50%);
top: 50%;
left: 50%;
font-size: 10px;
font-family: Verdana, sans-serif;
}

input:checked+.slider .on {
display: block;
}

input:checked+.slider .off {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<label class="switch">
<input type="checkbox" id="togBtn">
<div class="slider round">
<span language='japanese' class="on">JPN</span>
<span language='english' class="off">ENG</span>
</div>
</label>

<ul class="nav-items">
<div class="content">
<h2 class="title">Hello World</h2>
</div>
</ul>

Simplest way to create multiple-language one-page website

I'm not sure if this is efficient but since you have very little text, This will work.

// Maintain a supported Language List
var langList = ['en', 'zh'];
// Get browser Language
var userLang = navigator.language || navigator.userLanguage;
// extract Language (en-US => en)
userLang = userLang.substring(0, 2);
// Call the function to set language
changeLang(userLang);

// function to change language
function changeLang(lang) {
langList.forEach((langEle) => {
// if language matches, display
if (langEle == lang) {
var langElems = document.querySelectorAll('.' + langEle)
langElems.forEach((elem) => {
elem.style.display = "block"
})
}
// hide the language text
else {
hideLang(langEle)
}
})
}

// function to hide language
function hideLang(lang) {
var langElems = document.querySelectorAll('.' + lang)
langElems.forEach((elem) => {
elem.style.display = "none"
})
}
<h1><span lang="en" class="en">Hello</span> <span lang="zh" class="zh">你好</span></h1>
<button onclick="changeLang('en')">English</button><button onclick="changeLang('zh')">Chinese</button>


Related Topics



Leave a reply



Submit