First of all I want to say that I have a website where I want to change the language without reloading the page. That is why I inserted buttons for EN and DE.
<button lang="de" class="btn btn-primary btn-sm language" >DE</button>
<button lang="en" class="btn btn-primary btn-sm language" >EN</button>
Furthermore my CSS looks like this:
html.en :lang(de) {
display: none;
}
html.de :lang(en) {
display: none;
}
And that is my JQuery script:
if ($("html").hasClass('de')) {
$('html').addClass('de');
}
else{
$('html').addClass('en');
}
$('.language').click(function(){
($('html').toggleClass('de en'));
});
And finally here is my html tag:
<html class="">
My Problem is that if I change the language on one page it automatically changes back if I click on a link to a new page. I know there is a problem with my JQuery if function. But I really do not know how to solve this. Maybe with JQuery cookies?
Yes - every page load will result in a new JavaScript scope. If you need to maintain any state between pages, you'll need to use cookies or keep something appended on to the URL between pages. (Even if using server-side components, a client-side identifier is typically required to keep a session ID for the server to relate back to.)
https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API may also be of interest.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With