Javascript set language function issue

Joined
Nov 24, 2024
Messages
2
Reaction score
0
Hello so i'm coding a project and ran into a issue that neither me or AI can identify lol i'm coding python scripts mostly i'm not a frontend guy...but got to code a website. what i am doing worked fine before then just stopped working and i got no errors or anything else...

the issue is i'm using a
<select id="selected_lan">
<option value="#sv">Svenska</option>
<option value="#eng">English</option>
</select>

in the html code to pick a language on the website. and when i set on the

const selection_dropdown = $('#selected_lan');

selection_dropdown.on('change', function() {
var selectedValue = $(this).val();
window.location.hash = selectedValue; // Change the hash to the selected value
setLanguage(selectedValue); // Update the language immediately
console.log("switched to:", selectedValue);
});

and it won't activate the handler really it seems like. can't figure out the issue it displays no errors in the console...so i usually don't code JS but i don't get it.... shouldn't it display any type of error if something is wrong always? i have been going through the code several times and see nothing wrong. i tried f5 for updating the page and tried in different web browsers etc....as i said it worked earlier without issues...

here is the code:


appreciate the help. Thank you :)
 
Joined
Nov 24, 2024
Messages
2
Reaction score
0
okay everyone it's solved now....finally figured out the issue...as mentioned i'm not experienced with js and web in general...i was appending the dropdown to a div element which caused issues. Now i set it o a fixed position instead of appending anywhere. works fine now..took me a while to figure out...
 
Joined
Jul 4, 2023
Messages
503
Reaction score
63
You can achieve this multilingual effect on a website, for example, as follows:

[ vanilla javascript: on-line ]
HTML:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
      header,
      main {
        width: 80dvw;
        max-width: 80dvw;
        margin: 1rem auto;
        background-color: whitesmoke;
        padding: .5rem 1rem;
      }
      nav ul {
        display: flex;
        justify-content: space-between;
        list-style: none;
        margin: 0;
        padding: 0;
      }
      #selected-language {
        background-color: transparent;
        padding: .25rem 0 .25rem 1.5rem;
        font-size: 300 .8rem/1 system-ui, monospace, sans-serif;
        background-repeat: no-repeat;
        background-position: .25rem center;
        background-size: 20px 15px;
      }
    </style>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li>
            <h1 data-lang="hello-message"></h1>            
          </li>
          <li>
            <select id="selected-language">
              <option value="sv">Svenska</option>
              <option value="en" selected>English</option>
            </select>
          </li>
        </ul>
      </nav>
    </header>
    <main>
      <p data-lang="welcome-message"></p>
      <button data-lang="shop-button"></button>
      <article>
        <p data-lang="services1"></p>
      </article>
      <article>
        <p data-lang="services2"></p>
      </article>
      <article>
        <p data-lang="services3"></p>
      </article>
    </main>

    <script>
      const languages = {
        en: {
          'hello-message': 'Welcome to our website in English',
          'welcome-message': 'Randomly crafted phrases fill this space, generating meaningless but readable lines for layout testing. Elegant structures and proper forms bring visual balance. Quickly imagined, no context appears, yet flow remains intact. Placeholder sentences endlessly circle to display page aesthetics perfectly.',
          'shop-button': 'Shop lorem',
          'services1': 'Simple words arranged for clarity, testing layouts and spacing with ease. Placeholder lines help visualize',
          'services2': 'Random text <b>fills</b> design gaps, shaping structure and style. Use this for templates and creative views.',
          'services3': 'Crafted words form <i>flowing ideas</i>, fitting seamlessly in layouts. Placeholder writing for clean visuals.',
          'country-flag':'https://flagcdn.com/w40/gb.png'
        },
        sv: {
          'hello-message': 'Välkommen till vår webbplats på svenska',
          'welcome-message': 'Slumpmässigt utformade fraser fyller detta utrymme och skapar meningslösa men läsbara rader för layouttestning. Eleganta strukturer och korrekta former skapar visuell balans. Snabbt föreställda, inget sammanhang uppstår, men flödet förblir intakt. Platshållartexter cirkulerar oändligt för att visa sidans estetik perfekt.',
          'shop-button': 'Handla lorem',
          'services1': 'Enkla ord arrangerade för tydlighet, testar layouter och mellanrum med lätthet. Platshållarlinjer <b>hjälper</b> visualiseringen.',
          'services2': 'Slumpmässig text fyller designluckor, formar struktur och stil. Använd detta för mallar och kreativa vyer.',
          'services3': 'Skräddarsydda ord bildar flödande idéer och passar sömlöst i layouter. Platshållarskrift för rena visuella effekter.',
          'country-flag':'https://flagcdn.com/w40/se.png'
        }
      };

      window.onload = () => { setLanguage() };

      function setLanguage(lang='en') {
        Object.keys(languages[lang]).forEach((key) => {
          switch(key) {
            case 'country-flag':
              document.querySelector('#selected-language')
                .style.backgroundImage = `url('${languages[lang]['country-flag']}')`;
              document.documentElement.lang = lang;
              break;
            default:
              const element = document.querySelector(`[data-lang="${key}"]`);
              if (element) element.innerHTML = languages[lang][key];
          }
        });
      }

      document.querySelector('#selected-language')
        .addEventListener('change', function() {
        setLanguage(this.options[this.selectedIndex].value);
      });
    </script>
  </body>
</html>

[ jQuery: on-line ]
HTML:
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">

    <style>
      header,
      main {
        width: 80dvw;
        max-width: 80dvw;
        margin: 1rem auto;
        background-color: whitesmoke;
        padding: .5rem 1rem;
      }
      nav ul {
        display: flex;
        justify-content: space-between;
        list-style: none;
        margin: 0;
        padding: 0;
      }
      #selected-language {
        background-color: transparent;
        padding: .25rem 0 .25rem 1.5rem;
        font-size: 300 .8rem/1 system-ui, monospace, sans-serif;
        background-repeat: no-repeat;
        background-position: .25rem center;
        background-size: 20px 15px;
      }
    </style>
  </head>
  <body>
    <header>
      <nav>
        <ul>
          <li>
            <h1 data-lang="hello-message"></h1>            
          </li>
          <li>
            <select id="selected-language">
              <option value="sv">Svenska</option>
              <option value="en" selected>English</option>
            </select>
          </li>
        </ul>
      </nav>
    </header>
    <main>
      <p data-lang="welcome-message"></p>
      <button data-lang="shop-button"></button>
      <article>
        <p data-lang="services1"></p>
      </article>
      <article>
        <p data-lang="services2"></p>
      </article>
      <article>
        <p data-lang="services3"></p>
      </article>
    </main>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>

    <script>
      const languages = {
        en: {
          'hello-message': 'Welcome to our website in English',
          'welcome-message': 'Randomly crafted phrases fill this space, generating meaningless but readable lines for layout testing. Elegant structures and proper forms bring visual balance. Quickly imagined, no context appears, yet flow remains intact. Placeholder sentences endlessly circle to display page aesthetics perfectly.',
          'shop-button': 'Shop lorem',
          'services1': 'Simple words arranged for clarity, testing layouts and spacing with ease. Placeholder lines help visualize',
          'services2': 'Random text <b>fills</b> design gaps, shaping structure and style. Use this for templates and creative views.',
          'services3': 'Crafted words form <i>flowing ideas</i>, fitting seamlessly in layouts. Placeholder writing for clean visuals.',
          'country-flag':'https://flagcdn.com/w40/gb.png'
        },
        sv: {
          'hello-message': 'Välkommen till vår webbplats på svenska',
          'welcome-message': 'Slumpmässigt utformade fraser fyller detta utrymme och skapar meningslösa men läsbara rader för layouttestning. Eleganta strukturer och korrekta former skapar visuell balans. Snabbt föreställda, inget sammanhang uppstår, men flödet förblir intakt. Platshållartexter cirkulerar oändligt för att visa sidans estetik perfekt.',
          'shop-button': 'Handla lorem',
          'services1': 'Enkla ord arrangerade för tydlighet, testar layouter och mellanrum med lätthet. Platshållarlinjer <b>hjälper</b> visualiseringen.',
          'services2': 'Slumpmässig text fyller designluckor, formar struktur och stil. Använd detta för mallar och kreativa vyer.',
          'services3': 'Skräddarsydda ord bildar flödande idéer och passar sömlöst i layouter. Platshållarskrift för rena visuella effekter.',
          'country-flag':'https://flagcdn.com/w40/se.png'
        }
      };

      $(document).ready(function () {
        setLanguage();

        function setLanguage(lang='en') {
          $.each(languages[lang], function (key, value) {
            switch (key) {
              case 'country-flag':
                $('#selected-language').css('background-image', `url('${value}')`);
                $('html').attr('lang', lang);
                break;
              default:
                $(`[data-lang="${key}"]`).html(value);
            }
          });
        }

        $('#selected-language').on('change', function () {
          setLanguage($(this).val());
        });
      });
    </script>
  </body>
</html>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,039
Messages
2,570,376
Members
47,032
Latest member
OdellBerg4

Latest Threads

Top