Search code examples
javascriptlang

change Language without leaving current page - JavaScript


I have a website with a language selector. It works great, except that whenever I do change language, it always redirects back to the root page as opposed to staying on whichever current page the user is on. How can I go about fixing this? Here is my code:

function checkLanguage() {
    let lang = localStorage.getItem('lang');
    let urlLang = window.location.pathname.split('/')[1];

    if(isNullOrWhitespace(urlLang)) {
        if (!lang) {
            lang = navigator.language.toLocaleLowerCase();
        }
        if (lang) {
            let userLang = languageDictionary[lang];
            changeLanguage(userLang);
        }
    }
    else {
        localStorage.setItem('lang', urlLang);
    }

    var windowWidth = $(window).width();

    if (windowWidth < 500 && lang === 'th-th') {
        $('.integrations-container').css('display', 'none');
    };
};

function isNullOrWhitespace( input ) {
    return !input || !input.trim();
}

checkLanguage();

// Changing language
function changeLanguage(lang) {
    if (languageOptions.indexOf(lang) === -1) {
        return;
    }
    localStorage.setItem('lang', lang);
    window.location.href = '/' + lang;
}

languageOptions = ['en', 'zh-cn', 'zh-hk', 'jp-jp', 'ko-kr', 'th-th'];

languageDictionary = {
    'en': 'en',
    'en-gb': 'en',
    'en-us': 'en',
    'zh-cn': 'zh-cn',
    'zh-hk': 'zh-ch',
    'ko-kr': 'ko-kr',
    'th-th': 'th-th',
    'jp-jp': 'jp-jp',
} 

Thank you kindle in advance! Also I am very new, so laymens terms is always appreciated :)


Solution

  • window.location.href = '/' + lang;
    

    I think this line is always redirecting back to top page when language is changed. It would be helpful if you can provide the example url of the page.

    Try change it to below to redirect to current page when language is changed. I think it should work in top page too.

    // Changing language
    function changeLanguage(lang) {
        if (languageOptions.indexOf(lang) === -1) {
            return;
        }
        localStorage.setItem('lang', lang);
    
        var urlData = window.location.pathname.split('/'); // /en/detail/test.html -> ["", "en", "detail", "test.html"]
        urlData.splice(0, 2).join('/'); //cut out ["", "en"]
        var newPath = urlData.join('/'); // detail/test.html
    
        window.location.href = '/' + lang + '/'+ newPath; // /jp-jp/detail/test.html
    }