F
F
Faber Estello2018-02-10 11:31:05
JavaScript
Faber Estello, 2018-02-10 11:31:05

Changing languages ​​on the client side - JavaScript (jQuery)?

I want to change the language on the page on the client side. Only one article came across - on habré , but there is no longer an example there.

If, for example, the page is in Russian initially:

<p lng="rus">
Привет Мир
Некоторый текст
</p>


Example code:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script type="text/javascript">
    var LANGUAGE = false;
    $.redrawLanguage = function (lang) {
      $.ajax({
        url : 'languages/' + lang + '.json', //тянем файл с языком
        dataType : 'json',
        success : function (response) {
          LANGUAGE = response; 
          $('body').find("[lng]").each(function () {
            var lng = LANGUAGE[ $(this).attr('lng') ]; 
            var tag = $(this)[0].tagName.toLowerCase();
            switch (tag) {
              case "input":
                $(this).val(lng);
                break;
                default:
                $(this).html(lng);
              break;
            }
          });
        }
      });
    }

    $.getLanguage = function (key) {
      if (typeof(LANGUAGE[key]) != 'undefined') {
        return LANGUAGE[key]; 
      }
      return key; 
    }
  </script>


There are links:

<a href="#" class="link" id="ru">RU</a>
<a href="#" class="link" id="en">EN</a>


I launch like this:

$('#ru').on('click', function(e){
    e.preventDefault();
    $.redrawLanguage('eng');
});

$('#en').on('click', function(e){
    e.preventDefault();
    $.redrawLanguage('rus');
});


There are no errors, but no changes occur.

Does anyone have an example for this article, because there are problems with the example?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dima, 2018-02-12
Dolgoter @DDolgy

In the old days I did it simply, without these habrs of yours. There are ru eng classes each in an element with its own text. And by clicking on the American flag, classes ru were forged and vice versa)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question