Skip to content Skip to sidebar Skip to footer

Dropdown Menu On Refresh Changes Javascript

I have implemented a navbar uisng bootstrap 4,in which I have a language dropdown, on selection translates the page, When dropdown language is selected, the url will change and dr

Solution 1:

I'm not super familiar with .ejs, but (looking at the other code you posted in your comment) it seems like you should be able to "pass along" the selected language from req.params.lang and then have it available in your .ejs-templates.

Something like:

router.get('/:lang', function (req, res) {
    const languageMap = {
      "en": "English",
      "fr": "French"
    };

    const selectedLang = req.params.lang;
    const name = languageMap[selectedLang];
    // pass the value down to index.ejs which in turn renders header.ejs 
    res.render('index.ejs', { selectedLanguageName: name });
});

And then in your header.ejs. You should have selectedLanguageName available to you, using the <%= yourVariableNameHere %> syntax

<button id="language" class="btn btn-warning dropdown-toggle" type="button" id="dropdownMenu2"
    data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" onclick="clickButton()">
    <%=  selectedLanguageName %>
  </button>
  <div id="languagelist" class="dropdown-menu" aria-labelledby="dropdownMenu2" onclick="clickItem(); return false">
    <a class="dropdown-item" href="/en">English</a>
    <a class="dropdown-item" href="/fr">French</a>
  </div>

I found some useful information in this tutorial: https://scotch.io/tutorials/use-ejs-to-template-your-node-application

It's possible that because index.ejs is includes as a "partial" you have to explicitly pass down the variable to it when you include it.

<%- include('header.ejs', {selectedLanguageName: selectedLanguageName}); %>

or something like it.

Ejs seems to have pretty good documentation for the basics, it's propably worth checking out https://ejs.co/#docs


Solution 2:

You're changing the page, so the javascript you're running won't do anything after you click, you should change the button's text via the server when the page loads, based on the path. But, here's a solution with javascript (not optimal because it requires the page to load first):

let languageMap = {
    "en": "English",
    "fr": "French"
};

document.querySelector('#language').innerText = languageMap[location.pathname.substr(1, 2)]; // Get the language short from the 2 first characters after the / in the URL

Post a Comment for "Dropdown Menu On Refresh Changes Javascript"