Tips for ensuring that your website can recall which call-to-action (CTA) has been selected for redirection

I'm attempting to create a bilingual webpage in Spanish and English. My goal is to have a main page where the user selects the language, and once chosen, the page remembers the language preference for future visits instead of prompting the choice again.

What would be the most effective way to achieve this?

EDIT-- I followed advice to use localStorage, but as someone unfamiliar with JavaScript, I've hit a roadblock. While I can input 'es' or 'en' into the 'locale', I am unable to redirect at all. Here is the code snippet:

<script>
    (function (){
  'use strict';

  var eng = document.querySelector('.eng')

  function setLocalStorage(){
     eng.addEventListener('click', () => {
      localStorage.setItem('locale','en')
    })
  }
  setLocalStorage()

}());
        (function (){
  'use strict';

  var esp = document.querySelector('.esp')

  function setLocalStorage(){
     esp.addEventListener('click', () => {
      localStorage.setItem('locale','es')
    })
  }
  setLocalStorage()

}());
        if (localStorage.getItem('en') === 'en') { window.location='eng.html'; }
        if (localStorage.getItem('es') === 'es') { window.location='esp.html'; }
    </script>

Answer №1

If you want to store data locally, consider using the localStorage feature. Check out: mdn localStorage

localStorage.setItem('language', 'en'); // or 'es'

Next time you visit the page, retrieve the stored value:

localStorage.getItem('language'); // --> returns 'en' 

(Note: On the first visit, your getItem call will return undefined.)

You can integrate this functionality into your code like so:

(function () {
  'use strict';

  const language = localStorage.getItem('language');

  if (language === 'en') {
    window.location = 'eng.html';

  } else if (language === 'es') {
    window.location = 'esp.html';

  } else {
    // First time visitor:

    document
      .querySelector('.eng')
      .addEventListener('click', () => {
        localStorage.setItem('language', 'en')
      });

    document
      .querySelector('.esp')
      .addEventListener('click', () => {
        localStorage.setItem('language', 'es')
      });    
  }

}());

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

Obtain a filtering dropdown list directly from the database within Ag-grid

Currently in my interface, I am attempting to implement a filter for the FOLDER column. This filter is supposed to retrieve data from the database and present it in a dropdown checkbox within that column. The filtering should be based on the selected data. ...

Dealing with multiple v-on:click events in Vue.js

Can I add multiple v-on:click events to the same element? I want to toggle a navigation menu and trigger a CSS animation on the element that toggles the navigation. <template> <div> <nav v-if="visible"> <ul&g ...

Real-time Updating of ChartJS Charts in Rails Using AJAX

I am currently working with Rails 5 and the latest version of ChartJS library (http://www.chartjs.org/docs/). My goal is to retrieve the most recent 20 items from the SensorReading model and update the Chart using setInterval and AJAX. I have successfull ...

Request for removal in Express.js

Currently in the process of developing a MERN-stack app, but encountering issues with the delete request function. Here is the relevant code snippet: Upon attempting to send a delete request via Postman, an error message is displayed. I have researched ...

How to implement hover effect to show child div within parent div using React.js

Hey there! I'm fairly new to working with react js and currently trying to add some animation to a nested div. The parent div, known as " portfolio-product-item ", showcases a featured image pulled from the WP REST API. Inside this parent div, there&a ...

Bootstrap 5 - Create a full-screen modal perfectly aligned with its parent element

BootStrap 5 Incorporating the following layout: <div class="row flex-nowrap"> <div class="left"> <!-- leftbar --> </div> <div class="main overflow-auto position-relative"> <!-- ...

Refreshing the identification of a button

I have been working on updating an ID with a value from another button. Here is my current progress: $('.viewemployment').on('click', function(e){ var url = '<?php echo Config::get('URL'); ?>dashboard/employmen ...

Jquery Autocomplete has the ability to store and recall previous user selections

When the region is selected, autocomplete addresses should be displayed. Each time the region changes, the Jquery autocomplete function is called. While I am able to get the correct autocomplete addresses for the current region, I also receive address list ...

Arranging Bootstrap divs vertically and then horizontally in mobile view

My website layout is relatively straightforward. It consists of a header at the top, a navigation bar with an image inside a column on the left, and the main content displayed on the right side. https://i.stack.imgur.com/yYzaG.png For mobile responsive vi ...

What might be causing the invisibility of a particular div element?

Here is the layout in the div element: <div class=" wrap clear"> <div class="block pink float"></div> <div class="block blue float"></div> <div class="block orange float"& ...

Dealing with Errors in Express 4

After reviewing several posts, I am still confused about how to handle errors. Here is a snippet of my middleware: // catch 404 and forward to error handler app.use(function (req, res, next) { var err = new Error('Not Found'); err.status ...

Angular application's HTML Canvas unexpectedly changes to a black color when I begin drawing

Currently, I am developing an Angular application in which users can draw text fields on PDF pages. To achieve this functionality, I have integrated the ng2-pdf-viewer library and created a PDF page component that incorporates an HTML canvas element. Howe ...

Child components are not able to access properties from the root component in VUE3

Hi there! I'm currently learning VUE3 and had a question about defining global properties in the Root Component. I did some research on Google before posting this question, but couldn't find any relevant results. I would like to set a global pro ...

Display a loading component within the navbar in React while waiting for data to be retrieved

I recently updated my navbar component to accept dynamic values for menu titles. One of these dynamic values is the username, which needs to be fetched asynchronously. To handle this, I decided to display a loading animation until the username is fully fet ...

Struggling to implement .indexOf() in conjunction with .filter()

Hello, I'm new to JavaScript and ES6. Currently, I am working on a react-native app that utilizes Firebase and Redux. One of my action creators acts as a search bar function to fetch data from Firebase. Here's the code I have so far: export cons ...

Eliminate any unnecessary tags located before the text

I am facing a challenge with the following code snippet. The Variable contains a string that includes HTML tags such as <img>, <a>, or <br>. My goal is to eliminate the <img> tag, <a> tag, or <br> tag if they appear befo ...

Achieving a bold border on top of an image without altering the image's dimensions

I'm in need of Photoshop-like selection functionality, but when I add a border to the enclosing div that holds the image, the image ends up smaller by twice the thickness of the border. How can I fix this issue? I have attempted a solution by adding ...

Utilizing AJAX requests to execute create, update, and delete actions all from one streamlined file instead of separating them into three distinct

In my JavaScript code, I am currently making XMLHttpRequests to separate PHP files for different functionalities in my app - like add.php, update.php, and delete.php. However, having three separate files feels repetitive. Is there a way to consolidate al ...

The issue of ExpressionChangedAfterItHasBeenCheckedError is a common problem faced by Angular

I have implemented a component loading and an interceptor to handle all requests in my application. The loading component is displayed on the screen until the request is completed. However, I am encountering an error whenever the component inside my router ...

Error message: Vue warning - The prop "disabled" must be a boolean type, but a function was provided instead

I have this code snippet that I am currently using <v-list-item> <v-btn @click="onDownloadFile(document)" :disabled=getFileExtention >Download as pdf</v-btn > < ...