Change the language of the website using JavaScript/JSON

Creating a website and aiming to utilize JavaScript for the following:

If the browser language is set to French, retrieve the text from languageFr.json, otherwise, retrieve the text from languageEn.json.

Here is a snippet of the code I have so far:

JSON File

{
"h2": "random title",
    "p": lorem ipsum
}

JavaScript Code within the head of index.html

<script text="text/javascript">
    var lang;

    function detect() {
        var userLang = navigator.language || navigator.userLanguage;
        if (userLang == "fr") {
             lang = JSON.parse("languageFr.json");
        } else {
                 lang = JSON.parse("languageEn.json");
        }       
    }

    $(document).ready(detect());
</script>

Following this, in the body of my HTML:

<h2><script>document.write(lang.h2);</script></h2>

Despite this, the code doesn't seem to be functioning correctly. The console in Chrome indicates that lang is undefined. What could be the issue here?

Appreciate the assistance.

Answer №1

  1. Before the document is fully loaded, the code
    <h2><script>document.write(lang.h2);</script></h2>
    runs. This causes your detect method to not be called yet, and the lang variable remains uninitialized.
  2. The JSON.parse method is being used incorrectly.

Answer №2

It seems like there might be a timing issue with the Javascript code in this section

<h2><script>document.write(lang.h2);</script></h2>

The script in question appears to be executing before the necessary function has been fully processed.

Typically, Javascript will run as soon as the browser reaches it, causing the browser to momentarily pause parsing the page. On the other hand, the detect function seems to be waiting for the document ready event before executing.

This means that the document.write() call is happening before the detect() method is being called, leading to lang having no value.

Answer №3

It's true that Egor4eg has identified the problem (in fact, most of the answers have). I recommend exploring alternative methods for populating elements with language-specific text. Here's one approach:

<div class="i18nstring" data-message="h2"></div>

//Add this snippet at the end of your detect() function (to ensure it is only executed once the document is fully loaded)

$('.i18nstring').forEach(function() {
    $(this).text( lang[this.dataset.message] );
}

This solution may require some additional fine-tuning (especially regarding the data-message attribute) to ensure full cross-browser compatibility, but JQuery can assist with that. It's important to note that each i18nstring node doesn't necessarily have to be a div element.

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

Retrieve the highest value indexes from a three-dimensional array with JavaScript

In my dataset, I have an array structured like this: [34, 12, 56] [100,125,19] [30,50,69] The highest value in this array is 125, so the index [1,1] is returned. This means that 125, the highest value, can be found in row 1, column 1. To determine the i ...

Guide to writing a unit test for a parameter decorator in NestJs

I want to implement a unit test for a basic custom decorator that I created, but I'm facing some challenges. This decorator was developed based on the solution provided here. I have Keycloak authentication set up and using this solution in my controll ...

What could be causing my div to not appear when using jquery's show function?

I'm dealing with HTML code that looks like this: <div id="answerTypeSection" style="visibility: hidden"> <div class="row"> <div class="col-md-2">adfadfafasdfasdfas</div> </div> <label class="control-label"&g ...

Transform JSON keys into separate columns with predetermined titles in Pandas

Seeking a way to expand dataframe from JSON data with predefined values. The goal is to gather all the key values from the JSON data and use them as column headers. id |Name | MonthWise 0 |ABC |{'102022':{'val':100, 'count&a ...

Is the 'Document' term not recognized within expressjs?

I'm having trouble implementing a query selector in an ExpressJS application and it's not working // search products router.post('/search', function(req, res) { var db = req.db; var elasticlunr = require(&apo ...

endless cycle of scrolling for div tags

My goal is to incorporate a tweet scroller on I believe it uses the tweet-scroller from Unfortunately, this link seems broken as the demo is not functioning. I searched for an alternative solution and came across http://jsfiddle.net/doktormolle/4c5tt/ ...

The spinner persists even after the fetch api call

The issue I'm facing with my song lyrics app is that the spinner does not disappear after fetching data from the API. It seems like JavaScript is unable to detect the presence of the spinner even though it exists when the remove function is called. I ...

Change the content of an ion-card in Ionic2 dynamically

After fetching a list of books from the backend API provider, I am presented with sample data that looks like this: { "success":true, "books":[ { "id":1000, "book_code":"CC219102", "read_status":"completed", ...

updating the row of an html table with elements from a javascript object

I am faced with the task of dynamically adding rows to a table based on the number of elements in my JavaScript object. The object consists of keys and arrays of values. userobject={ ID: [1,2,3] IP_Address: ["12.21.12 ...

Is jQuery still recommended for adding animations in VueJS?

In my component's methods object, I currently have the following code snippet: startImageAnimation() { $('.splash-image').fadeIn(1400, () => { setTimeout(function() { $('.splash-image').fadeOut(1400, () ...

What is the method for transmitting a message from localhost to a React frontend?

I am currently running a WebSocket server that is receiving streams of messages from an MQTT source. These messages are then sent to a localhost server on port 8080. The messages being received are actually a stream of random numbers. Below is the Python ...

Accessing variables from child controllers with populated select inputs in Angular

I'm currently facing an issue involving 3 controllers: Parent Controller: DocumentController Child Controller1: XdataController Child Controller2: CompanyController The child controllers are used to populate data in three Selector inputs on the fron ...

How to access Bootstrap's modal initial data-* upon closing

When displaying a bootstrap modal, a convenient method to retrieve associated data is by using the following code snippet: $('#myModal').on('show.bs.modal', function (e) { var id = $(e.relatedTarget).data('id'); alert( ...

Apply the child's style if the parent's sibling contains the specified class

I am struggling to add the class "bold" to a child element (span) of a parent element (button.usa-nav-link). This parent element has a sibling (ul li.active) with the class .active. When the sibling is active, I want the child element's text to be bol ...

Parent controller was not in command before Child执行

When working with a parent view and a child view, I encounter an issue with accessing a json file. In the parent view, I retrieve the json file using the following code: $scope.services = Services.query(); factory('Services', function($reso ...

Incorporate highcharts data into your Laravel project using the power of AJAX

Encountering an issue with loading data for a Highcharts chart. The response from my controller provides the following data: [['Doctorado', 91.86],['Maestría', 6.98],['Licenciatura', 1.16]] Although the AJAX call is succes ...

JavaScript function unable to access static file for image

I need assistance with dynamically displaying an image (a checkmark or "X") based on a variable. When I insert the image using a script directly in the HTML file, it functions correctly. However, when attempting to set the image from within the createEasyD ...

Converting intricate JSON data to Gson format

I am dealing with a json data structure as shown below: { total_result: 46979, facet: [ { author: [ { writter1: 409 }, { writter2: 390 }, ...

Having trouble incorporating a variable into a jQuery selector

Trying to crack this puzzle has been an ongoing battle for me. I seem to be missing something crucial but just can't pinpoint what. I recently discovered that using a variable in the jQuery selector can make a significant difference, like so: var na ...

Use JavaScript to illuminate individual words on a webpage in sequence

Is there an effective method to sequentially highlight each word on a web page? I'm thinking of breaking the words into an array and iterating through them, but I'm not sure what the best approach would be. I have experience with string replacem ...