Issue
I want to create a simple CSS-based language switcher.
Consider a single static HTML page with content in, say, 3 languages:
<h1 lang="en">Hello World</h1>
<h2 lang="de">Hallo Welt</h1>
<h2 lang="fr">Bonjour la Mond</h1>
...
<p lang="en">This is my english webpage...</p>
<p lang="de">Dies ist meine deutsche Webseite...</p>
<p lang="fr">Je ne parles pas francais</p>
When the page loads, we want to detect the user's language (navigator.language || navigator.userLanguage
) and display only :lang(en)
elements hiding all german or french sections.
*[lang=en] {display:block}
*[lang=de] {display:none}
*[lang=fr] {display:none}
Now, if the user selects German, we want some JavaScript to switch the stylesheet out globally (not by element) so that we override the above CSS with:
*[lang=en] {display:none}
*[lang=de] {display:block}
*[lang=fr] {display:none}
How can one achieve such a CSS override globally in JavaScript?
Notes:
- I don't want to select HTML elements and toggle their display - I want to overwrite the global CSS.
- How the language is selected is irelevant - it will be an
onclick
oronchange
event which triggers the JS - I don't mind having all
lang
elements display as block though it would be interesting how to toggle their display property betweennone
and<original>
without losing saydisplay:inline
.
Solution
I can only say this is a costly idea but basically doable
const languages = ["en", "de", "fr", "ja"]
function changeLanguage(language) {
if (!languages.includes(language)) language = languages[0]
const style = document.querySelector("[data-type=css-language]") ?? document.createElement('style')
style.textContent = `[lang="${language}"] { display: block }`
style.setAttribute("data-type", "css-language")
document.body.appendChild(style)
}
changeLanguage(navigator.language)
[lang] { display: none }
<h1 lang="en">Hello World</h1>
<h2 lang="de">Hallo Welt</h1>
<h2 lang="fr">Bonjour la Mond</h1>
<h2 lang="ja">こにちは</h1>
...
<p lang="en">This is my english webpage...</p>
<p lang="de">Dies ist meine deutsche Webseite...</p>
<p lang="fr">Je ne parles pas francais</p>
<p lang="ja">私わオタク</p>
<button onclick="changeLanguage('ja')">Switch to Japanese</button>
Answered By - Tachibana Shin
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.