简体   繁体   中英

JS not executing the code when page loads or refresh

So I'm checking this code with a browser in english and it works fine, but when the browser is in pt-br it does not execute $('.translate').on("change", function(), so for the site to execute properly, when using a pt-br browser the user need to change to english and then portuguese to apply the portuguese option. if the user open with a pt-br browser the page should translate to the correspondent language, but it is just chaging the value in select and nothing else, how can I fix this?

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Multiple Languages with Jquery and Json</title>
  <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
  <select id="language" class="translate" style="">
    <option value="english">English</option>
    <option value="portuguese">Português</option>
  </select>

  <ul>
    <li class="lang" id="home">Home</li>
    <li class="lang" id="about">About Us</li>
    <li class="lang" id="contact">Contact Us</li>
  </ul>
  <p class="lang" id="desc">This is my description</p>

  <br>
  <script type="text/javascript">

    var arrLang = {
      'english': {
        'home': 'Home',
        'about': 'About Us',
        'contact': 'Contact Us',
        'desc': 'This is my description'
      },
      'portuguese': {
        'home': 'Lar',
        'about': 'Sobre',
        'contact': 'Contato',
        'desc': 'Essa é a descrição'
      }
    };

    // Process translation
    $(function() {
      $('.translate').on("change", function() {
        var lang = $(this).val();

        $('.lang').each(function(index, item) {
          $(this).text(arrLang[lang][$(this).attr('id')]);
        });
      });
    var userLang = navigator.language || navigator.userLanguage;
    $('.translate').val(userLang == "pt-BR" ? "portuguese" : "english");
    });
  </script>
</body>
</html>

This happens because the script is only executed when the input CHANGES.

To fix this, just execute the translation when page loads.

$(function() {
  const arrLang = {
    'en': {
      'home': 'Home',
      'about': 'About Us',
      'contact': 'Contact Us',
      'desc': 'This is my description'
    },
    'pt-BR': {
      'home': 'Lar',
      'about': 'Sobre',
      'contact': 'Contato',
      'desc': 'Essa é a descrição'
    }
  }
  const userLang = navigator.language || navigator.userLanguage;

  function changeLang(lang) {
    $('.lang').each(function(index, item) {
      $(this).text(arrLang[lang][$(this).attr('id')]);
    });
  }

  $('.translate').on("change", function() {
    changeLang($(this).val());
  });

  changeLang(userLang);
});

you are correctly binding the events and setting the value of the dropdown on page load, what you're missing is executing on page load the code that gets executed onchange of the select element.

After you set the value of the select element, you need to manually trigger the change event. I did it here (along with some optimizations)

// Process translation
$(function() {
  // grab a reference to the DOM elements
  var $translate = $('.translate');
  var $lang = $('.lang');
  // get the user language
  var userLang = (navigator.language || navigator.userLanguage) == "pt-BR" ? "portuguese" : "english";

  $translate
    // bind the change event
    .on("change", function() {
      var lang = $translate.val();
      $lang.each(function(index, item) {
        var $this = $(this);
        var id = $this.attr('id');
        $this.text(arrLang[lang][id]);
      });
    })
    // update the value of the language dropdown with the user lang (happens only on page load)
    .val(userLang)
    // trigger the change event so that the callback gets called (happens only on page load)
    .trigger("change");
});

Here's a working fiddle: https://jsfiddle.net/jaireina/0rxma3pg/42/

Good luck!

You use

if (userLang = "pt-BR")

But you have to use

if (userLang == "pt-BR")

To make it a compare

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM