Currently, I am in the process of implementing a language switch feature for a website project that I am currently working on. This feature will allow users to seamlessly switch between English, Latvian, and Norwegian languages. To achieve this functionality, I have developed a simple JavaScript code snippet that is designed to hide all language options within the HTML document and only display the selected one.
$('[lang="lv"]').hide();
$('[lang="no"]').hide();
$('#lang-switch').change(function() {
var lang = $(this).val();
switch (lang) {
case 'en':
$('[lang]').hide();
$('[lang="en"]').show();
break;
case 'lv':
$('[lang]').hide();
$('[lang="lv"]').show();
break;
case 'no':
$('[lang]').hide();
$('[lang="no"]').show();
break;
default:
$('[lang]').hide();
$('[lang="en"]').show();
}
});
[lang="lv"],
[lang="no"] {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<form class="lang-switch">
<select id="lang-switch">
<option value="en" onchange="en">EN</option>
<option value="lv" onchange="lv">LV</option>
<option value="no" onchange="no">NO</option>
</select>
</form>
Upon testing the implementation, I encountered an issue where selecting either the LV or NO language option after initially loading the site with English would result in all elements being styled with Style:display=none;
. However, despite thorough troubleshooting efforts, I have been unable to identify the root cause of this unexpected behavior.
My ultimate goal is to fine-tune the language switch functionality so that selecting a language from the form will effectively hide the English navigation bar while revealing the corresponding navbar for the chosen language.