How to do multi language sites?

@pauiprou

I did it like this

add a div to your page like this <div id="preloader"></div>
can be anywhere on the page

add this inline style to the head section

<style>
#preloader {
  position: fixed;
  inset: 0;
  z-index: 9999;
  overflow: hidden;
  background: var(--bs-tertiary-bg);
  transition: all 0.6s ease-out;
  width: 100%;
  height: 100vh;
}

#preloader:after {
  -webkit-animation-delay: -0.5s;
  animation-delay: -0.5s;
}

#preloader:before, #preloader:after {
  content: "";
  position: absolute;
  border: 4px solid #59bec5;
  border-radius: 50%;
  -webkit-animation: animate-preloader 2s cubic-bezier(0, 0.2, 0.8, 1) infinite;
  animation: animate-preloader 2s cubic-bezier(0, 0.2, 0.8, 1) infinite;
}

@keyframes animate-preloader {
  0% {
    width: 10px;
    height: 10px;
    top: calc(50% - 5px);
    left: calc(50% - 5px);
    opacity: 1;
  }
  100% {
    width: 72px;
    height: 72px;
    top: calc(50% - 36px);
    left: calc(50% - 36px);
    opacity: 0;
  }
}

.skiptranslate {
  opacity: 0;
  display: none;
  position: absolute !important;
  top: -5000px;
}
</style>

add this to a js-file

const lang = document.documentElement.getAttribute('lang') || 'en';
function Init() {
  new google.translate.TranslateElement({ pageLanguage: `${lang}` });
}

const usrlang = navigator.language.substring(0, 2) || navigator.userLanguage.substring(0, 2);
if (usrlang !== `${lang}`) {
  document.cookie = `googtrans=/${lang}/${usrlang}; Expires=Session; SameSite=None; Secure`;
  const google = document.createElement('script');
  google.type = 'text/javascript';
  google.src = 'https://translate.google.com/translate_a/element.js?cb=Init';
  document.body.append(google);
  setTimeout(removePreloader, 1200);
} else removePreloader();

function removePreloader() {
  const preloader = document.querySelector('#preloader');
  if (preloader) preloader.remove();
}

If the visitors browser language is different from the page language,
the google translate script will be injected into the page and the page will be translated to the visitors browser language and the preloader will be removed from the page

If the visitor has the same browser language as the page the preloader will be removed and no google script will be injected on the page

1 Like