Persist with displaying and concealing divs as we navigate through different pages

Incorporating a function into my main page has been successful so far, but I am seeking guidance on how to effectively utilize the function:

localStorage.setItem("language", selectedLanguage);

currentlanguage= localStorage.getItem("language"); 

My objective is to maintain the selected language when navigating from one page to another by clicking on a link.

For instance, if "en" is the default language, and I switch to "fr" on the main page and then move to another page, the language reverts back to "en". How can I utilize localStorage to retain the selected language?

Here is the link to the jsfiddle showcasing the function I am using:

https://jsfiddle.net/kodjoe/chvw181j/

HERE IS MY HTML CODE

<a class="button" id="en">EN</a>
<a class="button" id="fr">FR</a>
<a class="button" id="de">DE</a>


<div class="lan en">1</div>
<div class="lan fr">2</div>
<div class="lan de">3</div>
<div class="lan en">4</div>
<div class="lan fr">5</div>
<div class="lan de">6</div>

HERE IS MY JS

$(document).ready(function() {
$('.lan').hide();
$('.en').show();
});

$('.button').click(function(event) {
$('.lan').hide();
var selectedLanguage = $(this).attr('id');
var setActiveLanguage = "." + selectedLanguage;
$(setActiveLanguage).show();

localStorage.setItem("language", selectedLanguage);
currentlanguage= localStorage.getItem("language");
});

HERE IS MY CSS

.button { cursor:pointer; padding: 0px 30px; }

Answer №1

Storing the selected language in the browser's localStorage:

localStorage.setItem("language", selectedLanguage);

Retrieving the stored language preference from the localStorage:

currentLanguage = localStorage.getItem("language");

Answer №2

One effective method is to utilize SessionStorage, a feature documented on Mozilla Developer Network, to store crucial data such as the selected language. Afterwards, enhance your functions by incorporating if-clauses for determining the appropriate show/hide settings.

Answer №3

Storing code in a localStorage is an option, but a better approach would be to place it in a separate file meant for all global scripts. This way, you can easily manage and include all necessary scripts for your application. You can then link this file in the head section, most likely using an include for the header content.

<script src="js/globalScripts.js"></script>

//globalScripts.js

$(document).ready(function() {
    $('.lan').hide();
    $('.en').show();
});

$('.button').click(function(event) {
    $('.lan').hide();
    var selectedLanguage = $(this).attr('id');
    var setActiveLanguage = "." + selectedLanguage;
    $(setActiveLanguage).show();
});

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 could be causing the unexpected behavior of flexbox in Bootstrap?

I am facing a challenge while working on an existing PHP project that requires editing using HTML, bootstrap, and CSS. The flexbox is not behaving as expected, specifically when trying to display two cards in a row. Even though it works in a separate file, ...

Guess the Number Game with while Loop

I have a project where I need to limit guesses to 10, display the guessed number, and keep those results on the screen after each game without replacing the previous guesses. Each set of guesses should be numbered to show how many guesses have been made us ...

Unveiling the magic: Dynamically displaying or concealing fields in Angular Reactive forms based on conditions

In my current scenario, there are three types of users: 1. Admin with 3 fields: email, firstname, lastname. 2. Employee with 4 fields: email, firstname, lastname, contact. 3. Front Office with 5 fields: email, firstname, lastname, airline details, vendo ...

Styling for the bootstrap dropdown menu is missing

While attempting to incorporate a bootstrap dropdown menu, I noticed that despite applying the appropriate class to the sublist, the formatting and padding that is typically associated with bootstrap are not being retained. My current setup involves using ...

Guide on triggering a bootstrap modal by clicking on the image within an AngularJS application

In my angularjs project, I am currently working on a UI feature that involves cards. I have successfully implemented a modal box that opens when a button below the card image is clicked. However, I am looking to enhance the user experience by allowing th ...

Obtain content from a div element using jQuery

Here is a snippet of HTML code that I am working with: <!doctype html> <html> <head> <meta charset="utf-8" /> <title>Demo</title> </head> <body> <script src="jquery.js"></script> <scri ...

"Using JavaScript to Make Requests on Mobile Devices via HTTP

Greetings everyone, I have a query regarding implementing an endpoint api in my mobile application. For instance, suppose I have a server handling data and I want to notify my mobile application about new updates by sending a post request. Is this feasibl ...

Sending a notification alert directly to the client's web browser

My goal is to develop an application that allows Super users to notify other users by providing access to content, such as a PDF file, when they click on a link. For example, in the scenario where a teacher wants to share a PDF with students, this applica ...

Encountering issues while integrating jquery library into an asp.net 4.0 application

After creating an application in asp.net4.0, I utilized a master-page within the application. Incorporating a reference to a jQuery JS library file located in the Scripts folder on the master-page presented a challenge when attempting to write jQuery code ...

Issue encountered when attempting to utilize Next-Auth alongside Credentials Provider to authenticate within a pre-existing system

I am currently utilizing the Next-Auth Credentials provider for authentication purposes through our existing API. Following the guidelines provided at https://next-auth.js.org/configuration/callbacks the code snippet used is as follows: callbacks: { ...

Issue: The initial parameter should be a File or Blob object

Hey there! I'm currently utilizing the compressorjs plugin for compressing images, but I'm encountering an issue when selecting images. You can find out more about the plugin here. Here is my code snippet: window.resolveLocalFileSystemURL( ...

What is the best way to activate the default action/event of an HTML link (anchor element)?

Is there a way to programmatically trigger the default action of an HTML link using JavaScript or jQuery? Essentially simulating a user click on the link. Simply using .click() does not seem to do the trick. $('#alink').click(); // nothing happ ...

Position the input element in the middle of the div

Is it possible to center a form input element within a div element without it changing position when the browser window size is adjusted? I attempted using margin: auto and position: relative, but encountered issues with the element moving. How can this be ...

How do I specify a unique directory for pages in Next.js that is not within the src or root folders?

I'm currently facing an issue when trying to set a custom directory in Next JS. Although the default setup dictates that the pages directory should be located at the root or within the src directory, this arrangement doesn't fit my requirements ...

Utilizing GCE API within my website

Currently, my goal is to retrieve GCE information in a read-only manner to showcase infrastructure data on my website. To achieve this, I aim to acquire an OAuth2 token using the JS API and then transmit it to a Python Backend for GCE API calls. It's ...

Encountered a TypeError with mongoose: The function specified is not recognized as a valid function when attempting to create a new mongoose instance

I'm currently developing a web application using the MEAN stack, and I've encountered an issue with my mongoose instance that's giving me a headache. Let me share parts of my code: my route const express = require('express'); co ...

Analyzing critical code paths for optimal performance

There is a function that accepts two arguments and an optional third argument. The function should return true if the first argument is greater than the second, false if not, unless the third argument is true, in which case it should return true if the fir ...

Exploring the concept of $http/$q/promise in Angular

I am struggling to understand when $q/$http should trigger the onReject block. For example, if I have a simple call like this: $http.get('/users') .then(function(res) { return res.data; }, function(err) { console.log(err); }); If ...

Display WooCommerce notifications when using the AJAX add to cart feature

Looking to enhance my WooCommerce shop by incorporating AJAX functionality for the add to cart feature, I stumbled upon this incredibly useful tutorial which worked seamlessly. However, after implementing the solution, I noticed that the WooCommerce notic ...

Make an axios request multiple times equal to the number of items in the previous response

In my project, I am using the axios library to convert addresses into their respective coordinates. First, I fetch a list of addresses from an API. Next, I take the RESPONSE object and use Google API to convert each address to coordinates. Finally, I wan ...