Utilizing cache for the onclick function on a multilingual website

I am currently working on developing a multi-language index page with a language change area. When I click on each language text, the language changes as expected.

However, although the language changes when I click on my language links (AZ, EN, RU), it reverts back after a page reload. I am looking for a way to cache the onclick functions even after a page reload.

In addition, I would like to achieve this using pure JavaScript.

Below is the code snippet:

var voc = [
            {
              "AZ":"Log in2",
              "EN":"Log in",
              "RU":"Log in3"
            }
          ];

function translate(ele,lng){
 for(var i=0;i<voc.length;i++){
  for(var k in voc[i]){
   if(voc[i][k] == ele.innerText.trim()){
    ele.innerText = voc[i][lng];
    break;
   }
  }
 }
}
function translateTo(lng){
var trc = document.getElementsByClassName("trans");
for(var i=0;i<trc.length;i++){
translate(trc[i],lng);
}
}

//add the function below to any event handler such as button.onclick, select.change, or onload
//translateTo("AR");

function under1(){
  document.getElementsByClassName("lang")[0].style = "text-decoration:underline;";
  document.getElementsByClassName("lang")[1].style = "text-decoration:none";
  document.getElementsByClassName("lang")[2].style = "text-decoration:none";
}

function under2(){
  document.getElementsByClassName("lang")[0].style = "text-decoration:none;";
  document.getElementsByClassName("lang")[1].style = "text-decoration:underline";
  document.getElementsByClassName("lang")[2].style = "text-decoration:none";
}

function under3(){
  document.getElementsByClassName("lang")[0].style = "text-decoration:none;";
  document.getElementsByClassName("lang")[1].style = "text-decoration:none";
  document.getElementsByClassName("lang")[2].style = "text-decoration:underline";
}
.langselect a{
text-decoration:none;
}

.langselect a:nth-child(2){
text-decoration:underline;
}
<p>
<span class='trans'>Log in</span> 
</p>

<p class="langselect">
<a href="" class="lang" onclick='translateTo("AZ"); under1(); return false;'>AZ</a>
<a href="" class="lang" onclick='translateTo("EN"); under2(); return false;'>EN</a>
<a href="" class="lang" onclick='translateTo("RU"); under3(); return false;'>RU</a>
</p>

Answer №1

To implement this solution, you can utilize a cookie:

window.onbeforeunload = function() {
    document.cookie = "lang=AU"; //This is just an example. You have the flexibility to set the language as needed.
}

Then, upon page load:

window.onload = function() {
    window.getCookie = function(name) {
        var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
        if (match) {
            return match[2]
        };
}

Credit goes to @JonathanCamenisch for the latter part of the response.

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

Is there a way to display a modal newsletter popup just one time during a user's session?

I am trying to implement a modal popup that only shows once per session, but I am facing an issue where the div pops up every time I visit the homepage. My attempt to use cookies to fix this problem has not been successful. <script> if (!Cooki ...

Function defined as an AngularJS component

I am facing an issue where my component is not initializing when I create it with a function that returns a component object. Can someone please help me understand the difference between these two situations? Html: <div ng-app="demoApp"> <navb ...

Combining two observables into one and returning it may cause Angular guards to malfunction

There are two important services in my Angular 11 project. One is the admin service, which checks if a user is an admin, and the other is a service responsible for fetching CVs to determine if a user has already created one. The main goal is to restrict ac ...

Guide on displaying a list of images in a single line with rows and columns

I am in search of a solution to create the user interface depicted in the attached image using React. Additionally, this post includes a link to another post on the same site: How to add a single line image list that is horizontal scrollable (in react js). ...

Issue with CSS line height - Struggling to determine the precise number of lines

Despite finding an old post on this topic, the most popular answer and other solutions didn't work for many people. Even years later, I am still facing the same issue. My goal is to create a div that is precisely 19 lines tall (ideally aiming for 19. ...

"Turn a blind eye to Restangular's setRequestInterceptor just this

When setting up my application, I utilize Restangular.setRequestInterceptor() to trigger a function that displays a loading screen whenever a request is made with Restangular. Yet, there is a specific section in my application where I do not want this fun ...

Deselect the DOM element

Here is a jQuery code snippet: $(document).ready(function () { $(".story-area > h1, .story-area > p, .story-area > div > p").text(function () { return convertString($(this).text()); }); }); Additionally, there is a function de ...

The issue arises when attempting to reopen the jQuery UI dialog box after a div has been loaded

I am facing an issue with my survey results table where I have an EDIT button for each entry. Clicking on the EDIT button opens a dialog box with the survey results loaded from the database. After editing the answers, I want to save them in the database an ...

Expanding the functionality of a regular expression

My goal is to identify JavaScript files located within the /static/js directory that have a query string parameter at the end, denoted by ?v=xxxx, where 'x' can be any character or number. Here's an example of a match: http://127.0.0.1:8888 ...

Guidelines for Sorting Objects and Arrays in a JavaScript Array

I have a set of data that needs to be filtered based on specific parameters. While I can successfully filter through the initial value in the array, I am struggling to filter deeper into nested arrays. The dataset is structured as follows: let data = [ ...

capturing elements while showcasing others through CSS

I am facing a dilemma with my classes for the menu and content sections of my website. The menu is controlled by .site-header-menu class. Meanwhile, the content section is managed by the .content class. I want to know how I can target the .content when th ...

What causes the width of unrelated cells to change when the contents of colspan'd cells expand in IE7?

Before we delve into the details, I invite you to take a look at this fiddle using IE7. It's quite intricate and not something I want to repeat here. The main issue is that clicking on the red block should display additional information. The top row ...

transferring JSON information to a template in a NodeJs application

Currently, I am performing some filtering on my JSON data and storing the result in a variable called driver. The driver variable contains JSON data that I want to pass unchanged to the view. My main query is: How can I effectively send the data stored i ...

Utilizing a promise array in conjunction with v-data-table

In my custom table component, I am using a v-data-table to display data that is passed as a prop. I perform some data cleaning operations and then call an asynchronous function to fetch additional data from an API: //load cloud storage data const cleanData ...

Traverse through the nested JSON array using a loop

Exploring a JSON object: { "date_price": [ { "date": "Jan 2000", "price": 1394.46 }, { "date": "Feb 2000", "price": 1366.42 }, { "date": "Mar 2000", "price": 1498.58 }, { "date": "Apr ...

Having difficulty rendering the Three.js OBJ model

Greetings everyone, I recently attempted to load a 3D OBJ file using a Loader in my project. The console indicates that the 3D model and texture have been successfully loaded, but unfortunately, nothing appears on the screen. I extracted the 3D model and ...

RegEx for constraining string length

I am attempting to identify all instances where the length of a string is more than 1. This is the regex I am using: string.match(/\B\w+(?=\w)/gi); I also attempted this approach: string.match(/^\B\w+(?=\w){2,}$/gi); Unfor ...

Employing AJAX to extract data from SQL database and display it in a tabular format

I am working on creating a 2x2 table with labels in the first row and information from an SQL table in the second row. The goal is to display the Name of the business on the left and relevant information on the right. Each name will be clickable, triggerin ...

Having trouble determining the offsetHeight of an element within AngularJS

My directive, named 'myObject', is supposed to log the offsetHeight of its target element. However, it's not working as expected. I suspect it's because the height is being calculated before the element has any content. Is there a solu ...

Tips for resolving browser compatibility issues

Recently, I built a website for my own purposes using Mozilla Firefox. However, when I switched over to IE7, the entire site seemed to disappear. All the structure and alignments were completely thrown off. Can anyone offer suggestions to help me resolve ...