Attempting to establish a means to switch between languages

Currently, I am in the process of implementing a language switch feature for a website project that I am currently working on. This feature will allow users to seamlessly switch between English, Latvian, and Norwegian languages. To achieve this functionality, I have developed a simple JavaScript code snippet that is designed to hide all language options within the HTML document and only display the selected one.

$('[lang="lv"]').hide();
$('[lang="no"]').hide();

$('#lang-switch').change(function() {
  var lang = $(this).val();
  switch (lang) {
    case 'en':
      $('[lang]').hide();
      $('[lang="en"]').show();
      break;
    case 'lv':
      $('[lang]').hide();
      $('[lang="lv"]').show();
      break;
    case 'no':
      $('[lang]').hide();
      $('[lang="no"]').show();
      break;
    default:
      $('[lang]').hide();
      $('[lang="en"]').show();
  }
});
[lang="lv"],
[lang="no"] {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form class="lang-switch">
  <select id="lang-switch">
    <option value="en" onchange="en">EN</option>
    <option value="lv" onchange="lv">LV</option>
    <option value="no" onchange="no">NO</option>
  </select>
</form>

Upon testing the implementation, I encountered an issue where selecting either the LV or NO language option after initially loading the site with English would result in all elements being styled with Style:display=none;. However, despite thorough troubleshooting efforts, I have been unable to identify the root cause of this unexpected behavior.

My ultimate goal is to fine-tune the language switch functionality so that selecting a language from the form will effectively hide the English navigation bar while revealing the corresponding navbar for the chosen language.

Answer №1

To modify the language on the parent element (e.g. body), change some attribute and use CSS to style the rest.

If you want to keep information between page reloads, utilize localStorage.

// Execute immediately
(function () {
  // This will cause an error on StackOverflow.
  //let lang = localStorage.getItem('lang');
  let lang = null;

  $('#wrapper').attr('data-lang-main', lang != null ? lang : 'en');
})();

$('#lang-switch').change(function() {
  let lang = $(this).val();

  $('#wrapper').attr('data-lang-main', lang);

  // This will cause an error on StackOverflow.
  //localStorage.setItem('lang', lang);
});
[data-lang] {
  display: none;
}

#wrapper[data-lang-main="en"] [data-lang="en"] {
  display: initial;
}

#wrapper[data-lang-main="lv"] [data-lang="lv"] {
  display: initial;
}

#wrapper[data-lang-main="no"] [data-lang="no"] {
  display: initial;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form class="lang-switch">
  <select id="lang-switch">
    <option value="en">EN</option>
    <option value="lv">LV</option>
    <option value="no">NO</option>
  </select>
</form>

<div id="wrapper" data-lang-main="en">
  <span data-lang="en">Phrase EN</span>
  <span data-lang="lv">Phrase LV</span>
  <span data-lang="no">Phrase NO</span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is causing the issue where Multiple file selection does not work when using the multiple attribute

I am having issues with uploading multiple files on my website. I have created an input field with the attribute multiple, but for some reason, I am unable to select multiple files at once. app.html <input type="file" (change)="onChange($event)" req ...

Combining the power of AngularJS with the versatility of sails

A project I'm working on involves utilizing sails.js for back-end and AngularJS for front-end. My plan is to use the Yeoman-angular generator https://github.com/yeoman/generator-angular to create the Angular app first. Once the front-end development i ...

Guide on associating user IDs with user objects

I am currently working on adding a "pin this profile" functionality to my website. I have successfully gathered an array of user IDs for the profiles I want to pin, but I am facing difficulties with pushing these IDs to the top of the list of profiles. My ...

Add a class to a button in an Angular btn-group if a specific string is found within an

I am currently working on a project where I have multiple buttons that need to toggle an active class when selected in order to change their color. Below is a snippet of what I have: In the array called 'selected', I have: this.selected = [&ap ...

Assigning names to the points on the AxisHelper component in THREE.js

Take a look at the code snippet provided below: <html> <head> <title>My first Three.js app</title> <style>canvas { width: 100%; height: 100% }</style> </head> <body ...

Typescript - Error in Parsing: Expecting an expression

I am currently working with Vue and TypeScript and have encountered a problem. How can I resolve it? Here is the code snippet in question: private setTitle(systemConfig: any) { const systemConfigParse; let obj; systemConfigParse = JSON.parse(sy ...

Can we verify if this API response is accurate?

I am currently delving into the world of API's and developing a basic response for users when they hit an endpoint on my express app. One question that has been lingering in my mind is what constitutes a proper API response – must it always be an o ...

Implementing phone verification code delivery using ReactJS and Twilio client: Step-by-step guide

I've been scouring the internet for the past 8 hours and haven't been able to find a tutorial on using Twilio to send SMS messages with ReactJS. Does anyone know of a good tutorial for this? ...

Utilizing an EJS template within an express.js application to extract and assign data to a variable

Is there a way to transfer data from my node.js (express) app directly to a variable within the <script> tag on the page? On the server-side, I have the following code: let tmp = JSON.stringify(await f(i)); console.log(tmp); //correct data [{"i ...

What function does the sx prop serve in Material UI?

<Container style={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Container> <Container sx={{ margin: "10px" }}> <Article post={post} setCurrentId={setCurrentId} /> </Cont ...

Toggle button to create a fade in/out effect

Below is the HTML code snippet: <html> <head> <Script type = "text/javascript" src = "CprMdlrSrch.js"></Script> <link type="text/css"rel="stylesheet"href="CprMdlrSrch.css"/> </head> <body> <div id=" ...

Performing a modulo operation within a v-for loop

I'm showcasing divs in a loop and I need to assign classes based on the loop index. My goal is to have index 0 and 1 with the class col-6, then indexes 2,3,4 with the class col-4, followed by index 5 and 6 having the class col-6, and so forth. This w ...

Remove chosen tags from the options list in Material UI Autocomplete Multiple

When utilizing the Material UI Autocomplete for multiple values, the selected input is shown in the options list with a blue background color. Is there a way to configure the autocomplete to exclude already selected values from appearing in the options li ...

The parser encountered an unexpected token while attempting to parse the provided string

Struggling to correctly parse a JSON response from a server using node, as it is showing up as a string. Here's an example: "{name:'hello'}" Recreated the issue here: http://jsfiddle.net/x5sup14j/ Tried replace(/'/g, '"'); ...

Error encountered: Scrollanimation IOS syntax error- Unexpected token '=.' an open parenthesis '(' was expected before a method's parameter list

Encountering an issue with the scroll animation on older IOS devices (2019 and older) - I receive the following error message: SyntaxError: Unexpected token '='. Expected an opening '(' before a method's parameter list. class Event ...

Verify the HTML embed code with either PHP, JavaScript, or the Zend PHP framework

I have a quick question: Are there any effective methods for validating an HTML embed code? I am currently using Zend Framework and prototype+scriptaculous and would appreciate any hints or tips related to this environment. Thank you! ^^ ...

What is the best method for uploading a JSON file to a React web application and retrieving the file's link?

Is there a way to upload a JSON file to my React application and obtain the link to that file? Our app developer is working on implementing app linking and has requested this functionality. ...

The Mat table is not updating on its own

I am facing an issue in my Angular application where a component fetches a hardcoded list from a service and subscribes to an observable to update the list dynamically. The problem arises when I delete an element from the list, as it does not automaticall ...

Exploring the array mapping technique in React with nested objects

As part of a school project, I am working on creating a dashboard to visualize some data. I have successfully loaded the data into the front end using React. Now my goal is to retrieve specific values from a large array. However, I am uncertain about how ...

The two <p> elements are being pushed to the right column, which is not their intended display

A snippet of less.css code is available at this link: #content { overflow: hidden; width: 100%; p { float: left; width: 465px; padding: 0px 25px 0px 35px; margin: 0px; br { line-height: 2. ...