Translation of html page

Asked

Viewed 606 times

1

I am creating a Single page Application and in this project I am doing the translation of texts. Javascript

    var arrLang = {
        //=======================================================================================
        'en' : {
            'TitleSingUp' : "Don't have an account",
            'TxtSingUp' : 'To create a new accont, contact the back office team to get your credentials. then youll recive a ACTIVATION CODE valid for the first access only and the password settings',
            'Haveanaccount' :'Have an account',
            'TexLogIn' : 'If you have an accont, you can login in using your credentials. Make sure if your subscription is active and free from any restriction',
            'LogIn' :'Log IN',
            'SingUp' :'Sing UP',
            'Password' :'Password',
            'ForgotPassword' : 'Forgot Password',
            'SendmePassword' : 'Send me password',
            'PasswordSent' : 'Password sent',
            'PasswordNotSent' : 'Password not sent',
            'ValidEmail' : 'Enter a valid e-mail, the password will be sent to you.',
            'SendEmailSuccess' : 'Your password has been sent to your email successfully, access the mail account to recover',
            'EmailNotExist' : 'Your password has not been sent, this email does not exist',
            'AccountLocked' : 'Your password has not been sent, this account is locked',
            'MaxNumberAttemps' : 'Your password has not been sent, this account is locked the maximum number attemps has been exceeded',
            'IncorrectPassword' : 'For this user the password is incorrect, this is your attempt 2. The maximum number of attempts available is 3, for security reasons the account will be blocked after three failed attempts',
            //'' : 'For this user the password is incorrect, the number of attempts has exceeded the maximum allowed. For security reasons the account has been blocked.',
            'USerNotExist' : 'This user does not exist.',
            'accountExpired' : 'This account has expired',
            'ErrorSingIn' : 'Error SignIN!',

        },
        //=======================================================================================
        'it' : {

            'TitleSingUp' : 'Non hai un account',
            'TxtSingUp' : 'In caso di creazione di un nuovo account è necessario contattare il team di backoffice e fornire le proprie credenziali. A seguire verrà fornito il CODICE ATTIVAZIONE valido per il primo accesso e limpostazione della password.',
            'Haveanaccount' : 'Have an account',
            'TexLogIn' : 'Se possiedi un account puoi accedere utilizzando le credenziali in tuo possesso. Accertati che sia attivo e libero da qualsiasi blocco',
            'LogIn' : 'Log IN',
            'SingUp' : 'Sing UP',
            'Password' : 'Password',
            'ForgotPassword' : 'Password dimenticata',
            'SendmePassword' : 'Invia la mia password',
            'PasswordSent' : 'Password inviata',
            'PasswordNotSent' : 'Password non inviata',
            'ValidEmail' : 'Inserisci una email valida e ti invieremo la password',
            'SendEmailSuccess' : 'La tua password è stata inviata con successo, accedi allaccount di posta per recuperla',
            'EmailNotExist' : 'La tua password non è stata inviata, questa email non esiste',
            'AccountLocked' : 'La tua password non è stata inviata, questo account è bloccato',
            'MaxNumberAttemps' : 'La tua password non è stata inviata, questo account è bloccato il numero massimo di tentativi è stato superato',
            'IncorrectPassword' : 'Per questo utente la password non è corretta, questo è il tuo tentativo 2. Il numero massimo di tentativi a tua disposizione sono 3, oltre i quali laccount si bloccherà per motivi di sicurezza.',
            //'' : 'Per questo utente la password non è corretta, il numero di tentativi ha superato quello massimo consentito. Per motivi di sicurezza laccount è stato bloccato.',
            'USerNotExist' : 'Questo utente non esiste.',
            'accountExpired' : 'Questo account è scaduto',
            'ErrorSingIn' : ' Errore di SignIN!',

        },
        //=======================================================================================
        'pt' : {

            'TitleSingUp' : 'Não tem uma conta',
            'TxtSingUp' : 'Para criar um novo acesso , entre em contato com a equipe do back office para resgatar sua credencial. Então você receberá um codigo de ativação válidopara somente para o primeira configuração de acesso e senha será fornecida', 
            'Haveanaccount' : 'Já possui uma conta',
            'TexLogIn' : 'Se você já tem uma conta, você pode acessar usando suas credenciais. Sertifique-se seu cadastro está ativo e livre de qualquer restrição',                     
            'LogIn' : 'Log IN',
            'SingUp' : 'Sing UP',
            'Password' : 'Password',
            'ForgotPassword' : 'Esqueci minha senha',
            'SendmePassword' : 'Envie-me uma senha',
            'PasswordSent' : 'A senha foi enviada',
            'PasswordNotSent' : 'A senha não foi enviada',
            'ValidEmail' : 'ensira um email valido, a senha será enviada para você',
            'SendEmailSuccess' : 'Sua senha foi enviada para seu email com sucesso, acesse seu email para  resgatar',
            'EmailNotExist' : 'Sua senha não foi enviada, este email não existe',
            'AccountLocked' : 'sua senha não foi enviada , esta conta está bloqueada',
            'MaxNumberAttemps' : 'sua senha não foi enviada, esta conta está bloqueada, o número maximo de tentativas de acesso foi excedido',
            'IncorrectPassword' : 'A senha deste usuário está incorreta , esta é sua segunda tentativa. O numero maximo de tentativas são, por rasões de segurança a conta será bloqueada depois de três tentativas falhas.',                           
            //'' : 'A senha deste usuário esta incorreta, o número maximode tentativas permitidas foi excedido. Por momtivos de segurança a conta está bloqueada',           
            'USerNotExist' : 'Este usuário não existe',
            'accountExpired' : 'Esta conta expirou',
            'ErrorSingIn' : 'Erro de Sing IN!',

        }
    };


$(function(){
    $('.translate').click(function(){
        console.log("fui clicado");
        var lang = $(this).attr('id');

        $('.lang').each(function(index, element){
        $(this).text(arrLang[lang][$(this).attr('key')]);
        });
    });
});

HTML

 <legend class="title"><span class="lang" key = "LogIn">SING IN</span></legend>

But every time I change a page, the translation is lost...

How could I make the translation persist throughout the project ?

1 answer

3


Save the id on a sessionStorage and when opening the page check if it exists and fire the translation.

Create an anonymous function that does the translation and saves the id to a cookie sessionStorage:

function traduzir(lang){

   $('.lang').each(function(index, element){
      $(this).text(arrLang[lang][$(this).attr('key')]);
   });

   // salva o cookie
   sessionStorage.setItem("idioma", lang);
}

Call the function in the click event:

$('.translate').click(function(){
   var lang = $(this).attr('id');
   traduzir(lang);
});

Here you check if the cookie exists. If it exists, you call the function by sending the value of the cookie:

var language = sessionStorage.getItem("idioma");
if(language) traduzir(language);

The complete code will look like this:

$(function(){

    function traduzir(lang){

       $('.lang').each(function(index, element){
          $(this).text(arrLang[lang][$(this).attr('key')]);
       });

       // salva o cookie
       sessionStorage.setItem("idioma", lang);
    }

    $('.translate').click(function(){
       var lang = $(this).attr('id');
       traduzir(lang);
    });

    var language = sessionStorage.getItem("idioma");
    if(language) traduzir(language);

});

The sessionStorage is a temporary cookie. When you close the site it is lost. If you want a permanent cookie, just change it by localStorage.

  • 1

    One suggestion is to use Navigator language. If the app is in several languages.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.