Easy solution for a switcher between hiding and showing lang="" attributes with JS?

Viewed 30

I am looking for a fairly simple solution to show and hide lang="" specified DIV's (a switcher between the two). This must not be too hard, but I am a beginner in Javascript, and I couldn't find any proper resources. Does anyone have a suggestion?

:lang(eng) {
  display: block;
}

:lang(de) {
  display: none;
}

button {
  width:100px;
  height: 50px;
  background-color: blue;
}
button: active{
  background-color: green;
}

#example :lang(eng){
  width: 100vw;
  text-align: center;
  height: 50vh;
  background-color: yellow;
}
#example :lang(de){
  width: 100vw;
  text-align: center;
  height: 50vh;
  background-color: red;
}
<button onclick="myFunction()">English</button>
<button onclick="myFunction()">German</button>
<div id="example" lang="eng">
    <p>DIV with English text</p>
</div>
<div id="example" lang="de">
    <p>DIV with German text</p>
</div>

1 Answers

You need to select the HTML Element and set the specific attribute and insert the text:

const texts = { 
  "de": 'deutscher text',
  "en-us": 'english text'
}
function selectLanguage(lang) {
  const element = document.getElementById('example')
  element.setAttribute("lang", lang)
  element.innerHTML = texts[lang]
  console.log(document.getElementById('example'))
}
    <button onclick="selectLanguage('de')">German</button>
    <button onclick="selectLanguage('en-us')">English</button>
    <div id="example">
        <p>Text</p>
    </div>

Note that I store the texts in a simple object here. The usual way to store texts which should be available in multiple languages is to make use of a database like mysql or MongoDb.

I would also not use stylesheets to implement the language switchig feature. I have not much experience with multi language platform development but imho the styles should not have an effect to the websites logic.

If you have got any questions feel free to ask.

Edit: Generally you should not mix contents, logic and styles. You should always use the most practicle way to develop your website. If you intend to provide your content in multiple languages you should think about your architecture first. There are several different ways to achieve this kind of stuff. The internet is full of tutorials and guidelines :) Happy Coding!

Related