I have found many similar questions on this subject but none really answer my scenario so I decided to post a new question:
I have one page with several hidden sections (the same content in different languages). The hidden section displays based on a dropdown menu of languages (I'm using jQuery for that and it only hides/displays sections on the same page - the page URL stays the same) this is all working. However, I need to find a way to get people to arrive to the page with their language selected, not the default language which is English.
I would use either one of these: (example.com/page/#german) or (example.com/page/?german) but it then needs to hook into the existing jQuery and HTML so that that URL information selects the correct language. How can I do it?
This is the HTML of the language selector:
<select id="language_selector">
<option value="german">Deutsch</option>
<option value="english" selected >English</option>
<option value="spanish">Español</option>
<option value="french">Français</option>
</select>
and this is the jQuery code I am using to display only the selected language HTML content (based on ID):
hideAllDivs = function () {
$("#English").hide();
$("#French").hide();
$("#German").hide();
$("#Spanish").hide();
};
handleNewSelection = function () {
hideAllDivs();
switch ($(this).val()) {
case 'english':
$("#English").show();
break;
case 'french':
$("#French").show();
break;
case 'german':
$("#German").show();
break;
case 'spanish':
$("#Spanish").show();
}
};
I was thinking that the way to go about it would be to get the URL value, select the parameter only, and then pass that to the jQuery to select the right option but I have no clue how to do it, also without breaking my existing language selector (I still want people to be able to change their language manually)
CodePudding user response:
// url : 'example.com/page?language=german';
let language = (new URLSearchParams(window.location.search)).get('language') ?? 'english';
$('#language_selector').val(language);
handleNewSelection();