Adjust the language code in a URL using JavaScript or Node.js

Within my common header file, there is a navbar that includes a multilanguage dropdown menu. The issue I am facing is that when I select a language from the dropdown, the page translates correctly. However, when I navigate to other pages, the selected language does not carry over. For example, if I select 'th' on the first page, the subsequent pages should display '/th' instead of '/en'. Currently, the common header file always displays '/en', regardless of the chosen language in the dropdown. How can I use JavaScript to update all href links based on the selected language?

I need to dynamically update all href links when a specific language is selected from the dropdown.

//header.ejs
<body>
  <nav>
  <ul>
 <li class="nav-item">
            <a class="nav-link" href="/en/about" style="margin-right: 1.5rem!important;">about us</a>//change this link
          </li>
          <li class=" nav-item">
            <a class="nav-link" href="/en/contact"
              style="margin-right: 1.5rem!important;">contact us</a>
          </li>//change this link
  </ul>
    <div class="dropdown">
      <button id="language" class="btn btn-warning dropdown-toggle" type="button" id="dropdownMenu2"
        data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="clickButton()">
        English
      </button>
      <div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="clickItem(); return false">
        <a class="dropdown-item" href="javascript:" onclick="setLanguage('en')">English</a> 
        <a class="dropdown-item" href="javascript:" onclick="setLanguage('th')">Thai</a>
      </div>
    </div>
  </nav>
</body>

Answer №1

  1. Check if the language is set in the cookie when the page loads.
  2. Save the selected language in the cookie when the setLanguage function is called.

$(document).ready(function() {
  //read previously set cookie value
    var selectedLanguage = $.cookie( 'selectedLanguage' );
  // Check if the language is set in the cookie when the page loads.
     selectedLanguage = selectedLanguage ? selectedLanguage : 'en';
     setLanguage(selectedLanguage);
     
     
     function setLanguage(lan){
        $.cookie('selectedLanguage', lan);
     }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js" integrity="sha256-1A78rJEdiWTzco6qdn3igTBv9VupN3Q1ozZNTR4WE/Y=" crossorigin="anonymous"></script>

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

How can I properly connect my Facebook profile to my current account when utilizing JWT authentication?

I have extensively researched themes, but I am struggling to find a seamless way to connect an existing local strategy account with a Facebook strategy account. The issue lies in the fact that I am using JWT authorization. When a user clicks on the "Conne ...

Comparing Node.js streaming with the sendFile method

During my download speed tests, I compared using res.sendFile(src); and fs.createReadStream(src).pipe(res);, but didn't notice a significant difference. Which method is more efficient for serving files, and why? Will streaming be better suited for han ...

"Encountering HTTP 400 Bad Request Error When Using Flask and Ajax for Post Requests

I'm currently developing a small Flask-based website and I want to use Ajax to send data from the client to the server. So far, I've only used Ajax requests to fetch data from the server, but this time I want to submit data via a POST request. O ...

Utilizing Sequelize - Establishing relationships and querying data from related tables

I have successfully implemented 3 SQL tables with Sequalize, and here are the schemas: Loans id: DataTypes.INTEGER, book_id: DataTypes.INTEGER, patron_id: DataTypes.INTEGER, loaned_on: DataTypes.DATE, return_by: DataTypes.DATE, returned_on: DataTypes.DA ...

How does AngularJS watcher behave when a callback is triggered during a reload or router change?

Can anyone explain why the watch callback is triggered upon browser reload or Angular route change even when the old value and new value are the same? Here's an example: $scope.test = "blah"; $scope.watch("test", function(new, old){ console.log(ne ...

I'm looking to transfer my stringified object into the HTML body. How can I achieve

When sending an HTML file to a client using the res.write() method, I also need to include an object within the HTML. However, when I stringify the object and add it along with the HTML, the JSON object ends up outside of the HTML structure. I require the ...

Error 504 occurs on Express.js due to a timeout issue while a timer is active

Encountering a "504 Gateway Timeout" error on my Express.js application when a JavaScript timer is set to run every 20 seconds. Here is the code for my Express.js listener and the timer: const express = require('express') const app = express() ...

Creating a subtle vanishing popup dialog using only CSS (no reliance on jQuery)

Is there a way to add a fade effect to my simple pop-up image using CSS? I've tried various transition properties, but nothing seems to work. Any suggestions would be appreciated. Thanks! ...

Retrieve the current element when the key is released and send it as a parameter to a different function

Imagine a scenario where my website contains textbox elements that are dynamically generated, each with the class 'mytxt'. <input type="text" class="mytxt" /> <input type="text" class="mytxt" /> <input type="text" class="mytxt" /& ...

Issue encountered following the completion of the app's packaging with electron-packager

I'm a beginner with Electron, and so far I'm really enjoying using it. However, I have been facing issues when trying to package my apps. Initially, I thought the problem might be related to my code. To test this theory, I downloaded "https://git ...

Using async/await in React to retrieve data after a form submission

I am currently facing an issue with displaying data fetched from an API on the screen. My goal is to retrieve data when a user types something in a form and clicks the submit button. The error message I am encountering is: TypeError: Cannot read propert ...

Having trouble with positioning divs on top of each other? Struggling to get position absolute to work correctly?

Currently, I am utilizing flexbox to construct a grid layout. However, I have hit a roadblock when attempting to make the divs stack on top of each other. The overflow:auto is hidden and position relative has been added to the carddiv. While the divs are s ...

Only documents with a Mongodb type of string will be retrieved by this query

I'm facing an issue with retrieving a document using Postman based on a specific student number. When the student number is of type Int, it does not return anything. However, when I change it to String, everything works as expected. I am relatively ne ...

Send information to a different module

I've created a straightforward form component: <template> <div> <form @submit.prevent="addItem"> <input type="text" v-model="text"> <input type="hidden" v-model="id"> <i ...

The NW JS window loaded event fails to trigger when loading a URL, but functions properly when loading from a local

Having trouble triggering the loaded event on a live webpage compared to a local page. The loaded event fails to fire with this code: var mywin = nw.Window.open('http://www.google.com', {"frame": false}, function(testWin) { testWin.on(&apos ...

jQuery load() function triggers unexpected error in jQuery plugin

Here is the current structure of my page: <body> <div id="menuBar"> </div> <canvas id="myCanvas" width="700" height="700" style="border:1px solid #000000;"></canvas> </body> <script src="../Scripts/jQuery.mazeBo ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

Send the form via ajax

I am in the process of creating a unique application for my university, which is essentially a social network. One key feature I need to implement is the ability for users to add comments, which involves inserting a row into a specific database. To achieve ...

Comparison of loading time between loader gif and browser's loading image

Recently, I've come across a code snippet where I implemented a 'loader' gif to show while PHP retrieves data from an SQL database. Everything seemed to be working fine when testing on my localhost. However, upon closer observation, I notice ...

Does npm automatically delete itself when the ubuntu terminal is closed?

My current setup involves running Ubuntu 16.04 Xenial on VirtualBox. I've encountered an issue where after installing npm using the command: nvm install v8.1 the terminal recognizes commands like npm. However, if I close that specific terminal sessi ...