Auto language-switch on page load

Wondering if using jQuery is the best approach to create a single French page on my predominantly English website. I want it to work across multiple browsers on pageload, currently using HTML replace.

jQuery(function($) {
  $("body").children().each(function() {
    $(this).html($(this).html().replace(/Download/g, "FranceDownload"));
  });
  
  $("body").children().each(function() {
    $(this).html($(this).html().replace(/Document/g, "FranceDocument"));
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Onload this document will Translate to French.<br><br>
<div>Download - Document</div>

You can view the codepen example here: https://codepen.io/scottYg55/pen/dybOdgw

This method allows users to manually input words they want changed for language translation. Is there a more efficient way to achieve this? Should the script be fired each time?

Appreciate any suggestions or advice!

Answer №1

If you prefer not to rely on plugins and only need to translate the textual content, consider creating a small dictionary for your page. This method can handle HTML as well.

To simulate the onload function with a toggle button, you can use this function anywhere in your code where the dict object and lang variable are accessible.

The essential markup requirement is the data-translate attribute on the text-containing element and an entry in the dict object.

const dict = {
  "0": {
    en: "Download - Document",
    fr: "Télécharger - Document"
  },
  "1": {
    en: "It's not a document",
    fr: "Ce n'est pas un document"
  },
  "2": {
    en: "Translate this, while you<br />are fast asleep.",
    fr: "Traduisez ceci pendant que<br />vous êtes endormi."
  }
}

let lang = 'en'

const btnLang = document.getElementById('toggleLang')

// click event: toggle language
btnLang.addEventListener('click', function(e) {
  lang = lang === 'en' ? 'fr' : 'en'
  toggleLang(lang)
})

// toggle language (using lang variable and dict object)
function toggleLang(lang) {
  const toTranslate = document.querySelectorAll("[data-translate]")
  toTranslate.forEach(e => {
    e.innerHTML = dict[e.getAttribute('data-translate')][lang]
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Onload this document will Translate to French.<br><br>
<button id="toggleLang">Toggle language</button>
<div data-translate="0">Download - Document</div><br><br>
<div data-translate="1">It's not a document</div><br><br>
<div data-translate="2">Translate this, while you<br />are fast asleep.</div>

While this solution is simple and lightweight in terms of file size, it has its limitations. You must ensure that the dict object contains all elements referenced in the HTML and that each item includes all the desired language variations.

For a more comprehensive approach, consider exploring i18n for jQuery (, or ). i18n follows internationalization standards and is widely used in platforms like Wordpress (WPML), JS frameworks (such as VueJS: https://www.npmjs.com/package/vue-i18n). By familiarizing yourself with it now, you may find it beneficial for future projects. :)

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

Creating a seamless thread using AngularJS

I am working on a Spring MVC application that utilizes HTML and Angular on the client side. I have a method in my Angular controller that needs to run every 5 seconds. How can I achieve this using Angular? Thank you for your assistance. $scope.inspectio ...

Utilize JQuery to Extract HTML Elements

I'm working on developing a Chrome extension and one of my tasks is to extract specific text from the webpage I am currently visiting and store it in a variable. I have been attempting to achieve this using jQuery, however, none of the solutions I&apo ...

Checking the validity of email domains in real-time using Javascript

Is there a way to dynamically validate domains using JavaScript? I have a specific requirement which involves validating domains that are dynamically generated from user input. The goal is to match the domain with the company name selected and determine i ...

CSS | Creating gaps between elements within a form

My form is currently inside a flexbox card with two sides - left and right. The left side displays a picture, while the right side contains the actual input fields. I'm looking to add more space between the different inputs as they feel too cramped at ...

Expanding the sidebar panel during a redirection

I am facing an issue with the expansion panels in my sidenav. I have successfully been able to track and set their open state as they are opened and closed. However, when a list item within the panel is clicked and redirects to another route, the panel c ...

Accessing Facebook through the React create app login

I recently developed a React Webapp using the create-react-app module. My current challenge involves integrating Facebook login, but I'm encountering some obstacles. I am unsure about where to incorporate the Facebook JavaScript SDK asynchronously to ...

What is the best way to determine if a value from my array is present within a different object?

I have an array with oid and name data that I need to compare against an object to see if the oid value exists within it. Here is the array: const values = [ { "oid": "nbfwm6zz3d3s00", "name": "" ...

Does JavaScript Map Access Use Indexing for Efficient map.get Retrieval?

Is the map.get method in V8 optimized by indexing JavaScript-Map-object's keys, or does it loop through the entire map to find a key match? I'm curious about the efficiency of map.get with larger mappings containing 500,000+ key/value pairs. I h ...

MVC - The challenge of users repeatedly clicking the Submit button

In my MVC application, there are multiple pages where users submit a form by clicking a Submit button. Occasionally, users may click the button multiple times if they don't see an immediate response, causing the form to be submitted twice. To address ...

Find the index of the element that was clicked by utilizing pure JavaScript

I am struggling to find the index of the element that was clicked. Can anyone help me with this? for (i = 0; i < document.getElementById('my_div').children.length; i++) { document.getElementById('my_div').children[i].onclick = f ...

Footer refusing to stay fixed at the bottom of the viewport

Currently, I am utilizing fullpage.js with scrolloverflow.js activated on the second section. In this setup, I would like to have a footer that remains fixed at the bottom of the viewport for the second section only. However, instead of achieving this desi ...

Is it possible to run quirks mode in one frame while running standards mode in another?

Back in the IE6 days, I developed an old application that relies on frames instead of iframes and runs in quirks mode. Now, I'm wondering if it's possible to have one frame remain in quirks mode while another operates in standards mode when using ...

dual slider controls on a single webpage

I am attempting to place two different sliders on the same page. When I implement the following code for one slider, it functions correctly: <h3>Strength of Belief</h3> <div class="slidecontainer"> <div class="slider_left"> < ...

Hide a popup once a POST request is sent

My website features a login modal that appears when the user clicks on the login button. However, I encountered an issue where the modal remains open even after entering valid credentials and redirecting to another page. This problem persists regardless of ...

Chrome compatibility issue with margin collapsing

I'm currently working on a website and encountering a CSS issue. It appears fine in Firefox, but has some odd layout problems in Chrome. I would appreciate any assistance on how to resolve this issue. On the main page, if you scroll down, you'll ...

Tips for relocating anchor elements to less desirable locations

My website has an issue with anchor elements appearing too frequently and not in the desired location. I need someone to help fix this so there are only two anchors displayed. After checking my code, it seems like there are not more than the specified num ...

Achieving a fixed position within a div using CSS

Is there a way to arrange elements inside a div without modifying the HTML code? Yes, CSS can help you achieve this. Consider these blog posts: https://i.sstatic.net/7yTQ5.png The issue at hand is that the 'Read more' button gets pushed down wh ...

What is the reason for the binding event being triggered following the re-render of the setstate?

The Test component has a state of num. This component is designed to increase the value of num by 1 when a button is clicked. The button is linked to a self-increment method, and the keyup event is also connected to this method. When the method is triggere ...

Retrieve the values of the rows that have been selected in the Kartik GridView located within a modal, and then transfer

I am attempting to extract data from a Bootstrap modal (which contains a table of Kartik GridView) and pass the selected value to the parent form (an action create form). Can anyone provide guidance on how to achieve this? The modal form includes fields su ...

What methods are most effective for evaluating the properties you send to offspring elements?

Currently, I'm in the process of testing a component using Vue test utils and Jest. I'm curious about the most effective method to verify that the correct values are being passed to child components through their props. Specifically, I want to e ...