Running multiple languages locally may encounter issues, however, Codepen operates smoothly without any problems

While conducting research, I came across several options for creating multilingual websites. After implementing one method (jQuery), I noticed some slowness in translation and processing the information. Additionally, it only partially worked in the normal Chrome browser but worked fine in CodePen.

Here is the code I used:

var arrLang = {
  "hebrew": {
    "about": "עלינו",
    "poject": "פרוייקטים",
    "service": "שירותים",
    "contact": "צור קשר",
  },
  "english": {
    "about": "About",
    "poject": "Projects",
    "service": "Services",
    "contact": "Get In Touch",
  }
};
// The default language is English
var lang = "hebrew";
// Check for localStorage support
if('localStorage' in window){

   var usrLang = localStorage.getItem('uiLang');
   if(usrLang) {
       lang = usrLang
   }

}


console.log(lang);

        $(document).ready(function() {

          $(".lang").each(function(index, element) {
            $(this).text(arrLang[lang][$(this).attr("key")]);
          });
        });

        // get/set the selected language
        $(".translate").click(function() {
          var lang = $(this).attr("id");

          // update localStorage key
          if('localStorage' in window){
               localStorage.setItem('uiLang', lang);
               console.log( localStorage.getItem('uiLang') );
          }

          $(".lang").each(function(index, element) {
            $(this).text(arrLang[lang][$(this).attr("key")]);
          });
        });

This is the current result:

https://i.sstatic.net/fFLX4.png

When I click the English button to translate the content, it remains unchanged.

Here is the HTML:

<ul>
    <li><a href="#title" class="lang" key="about">About</a></li>
    <li><a href="#section1">Projects</a></li>
    <li><a href="#section2">Services</a></li>
    <li><a href="#section3">Get in Touch</a></li>
    <li><a href="#" class="translate" id="english">English</a>|<a href="#" class="translate" id="hebrew">עברית</a></li>
</ul>

The same code has also been uploaded to CodePen where it seems to be working fine.

How can I troubleshoot the translation issue that is occurring on local Chrome?

Answer №1

The following code snippet accomplishes the task you were aiming for.

I have assigned a class lang and a key attribute to each element that needs to be affected by the language. The key attribute contains the same key that was used for the translation in the arrLang object.

I have also added onClick events to the עברית | English links, passing the language that should be applied to the event handler function. The innerText of each lang element is then set to the corresponding value in the selected language.

Good luck! :D

var arrLang = {
  "hebrew": {
    "about": "עלינו",
    "project": "פרוייקטים",
    "service": "שירותים",
    "contact": "צור קשר",
  },
  "english": {
    "about": "About",
    "project": "Projects",
    "service": "Services",
    "contact": "Get In Touch",
  }
};

function applyLanguage(lang) {
  let langElements = document.getElementsByClassName('lang');
  Array.prototype.forEach.call(langElements, function(element) {
    let key = element.getAttribute('key');
    element.innerText = arrLang[lang][key];
  });
}

applyLanguage('english');
<ul>
  <li><a href="#title" class="lang" key="about">About</a></li>
  <li><a href="#section1" class="lang" key="project">Projects</a></li>
  <li><a href="#section2" class="lang" key="service">Services</a></li>
  <li><a href="#section3" class="lang" key="contact">Get in Touch</a></li>
  <li><a href="#" onClick="applyLanguage('english')" class="translate" id="english">English</a>|
    <a href="#" onClick="applyLanguage('hebrew')" class="translate" id="hebrew">עברית</a></li>
</ul>

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

Error message encountered when deploying a Discord bot on Heroku: "SyntaxError: Unexpected token '??='"

I encountered an issue when trying to deploy a Discord bot that I created using Node.js on Heroku. The error message is as follows: 2021-11-05T00:00:10.334347+00:00 app[web.1]: > node . 2021-11-05T00:00:10.334348+00:00 app[web.1]: 2021-11-05T00:00:10.3 ...

Using the power of ReactJS, efficiently make an axios request in the

After familiarizing myself with Reactjs, I came across an interesting concept called componentDidUpdate(). This method is invoked immediately after updating occurs, but it is not called for the initial render. In one of my components, there's a metho ...

HTML image identifier and canvas elements

Greetings! I have a question that I've been struggling to find an answer for on Google. I'm attempting to draw an image on a canvas and initially used the "new" constructor ( ballPic = new Image(); ballPic.src = "ball.png" ) which worked fine. Ho ...

Showing XML content with JavaScript

Trying to parse a simple XML list using JavaScript, but having trouble formatting it the way I need. <TOURS> <MONTH> <TOUR> <NUMBER>1</NUMBER> <VENUE>City Name - Venue Name</VENUE> < ...

Could not locate the provider: $stateProvider

It's puzzling to me why this code is not recognizing the $stateProvider. Uncaught Error: [$injector:modulerr] Failed to instantiate module app due to: Error: [$injector:unpr] Unknown provider: $stateProvider This is a simple example of a module: ( ...

How can I manually transclude content within a directive into two separate locations?

When trying to access the result of ng-repeat, I discovered that using the transclude function and manually compiling could help. However, this method does not work in situations with two places and elements containing ng-repeat. Here is how my code is str ...

Sending data through props to components that can only be accessed through specific routes

File for Router Configuration import DomainAction from './components/domainaction/DomainAction.vue' ... { path: '/domainaction' , component: DomainAction }, ... Linking to Routes using Router Links ... <router-link to="/domainact ...

Integrating Mailchimp with MongoDB and Node.js

As of now, I am managing a database of users in MongoDB and my goal is to provide them with regular updates on new content available on a real-estate marketplace website on a daily basis. My plan is to send out email notifications to each user every day w ...

Universal PM2 Configuration Settings in JSON Format

My current process involves initiating numerous Node.js processes using pm2. These processes are configured in a JSON file and started by executing pm2 start pm2.json Upon examining the JSON file provided below, it's evident that there is significan ...

Obtain the context within the image loading function

I am working with an array of Image objects: let imageArray = []; ... imageArray[i].onload = function () { ... } When the onload function is triggered, I need to determine which specific Image object it is referring to. Is there a method to achieve ...

What steps can be taken to delete a cookie when the server cannot be accessed?

Currently utilizing a node.js + express server and managing sessions for users who are logged in. I am curious about how a user can log out if the server becomes unreachable? In the usual method, I would simply call req.logout() on the request object in ...

Issue with SVG animation causing unnecessary duplication of circle shapes when utilizing animateMotion

I have implemented animateMotion to create an animation along a path. Below is the code snippet that demonstrates this: <!DOCTYPE html> <html> <head> <title>Example Of Many Things!</title> </head> <body> ...

Creating a Google Captcha with validation is a straightforward process that can enhance the

I am having issues with adding Google Captcha to my form. Despite all fields working properly, the Captcha integration seems to be causing some disruptions. I have included my code below. Thank you in advance for your help. Please also check the following ...

How to retrieve HTML attribute using D3 techniques

Looking to iterate through all rect nodes in the code snippet below: d3.selectAll("svg g rect") .on('mouseover', function (d) { console.log(this); }); When Console.log is executed, the following is printed: <rect class="cls" na ...

The true meaning of CSS3 transition is often misconstr

I'm trying to create a simple linear transition effect, but for some reason it's not working. Any suggestions on what might be causing the issue? HTML <div class="button-modern" style="background-color:#e73032"> <span style="color: ...

JavaScript threw an error with message: 'Unexpected identifier' that was not caught

Upon launching Web Developer in Firefox: SyntaxError: missing } after property list note: { was opened at line 7, column 7 ...

Expanding Vue Tabs with Bootstrap: Manipulating tab-content to perfectly fill parent height

On my webpage, I have implemented a tabs component called b-tabs. This component is enclosed within a parent div with a specific height. I am trying to make the content of the tabs take up the full remaining height of the parent component. https://i.ssta ...

Next.js Firebase Analytics Error: Undefined Window Object

I am currently working on implementing and exporting the Firebase analytics module in Next.js using Firebase v9. When attempting to run the code snippet below, I encountered an error message stating "ReferenceError: window is not defined". Howev ...

Troubleshooting a React JS and material-ui issue

Having an issue with material-ui integration in reactjs. Attempting to render a FlatButton, but encountering the error message: TypeError: _context$muiTheme is undefined As a newcomer to reactjs, I'm unsure of where the problem lies. Below is my code ...

Perform an AJAX request within a condition prior to executing the subsequent AJAX request

Within my database, I have two tables. When the submit button is pressed, I aim to insert a new trader into the trader table and retrieve the ID using laravel 5.2 by utilizing post ajax under certain conditions. Then, execute another post ajax for invoic ...