Streaming live at 10am (PST)

Multi-Language / Region - Create links from hreflang to same page on alternate language site

I was working on a multi-language site recently and wrote this piece of javascript to make it easier for users to change site language and get to the same content on the alternate language site.

As is standard practice for all multi-language sites, I have hreflangs set up on each page. I also have some links in the nav or footer to take users to other language home pages - these are static as they are on symbols.

I added the following attribute to each alternate language link - “data-language-link”=“fr” - “fr” in this example points to the French language site.

Then add this piece of code to the footer code, and it works!

// REDIRECT TO SAME PAGE ON ALTERNATE LANGUAGE SITE
var langLinks = document.querySelectorAll('a[data-language-link]');
var hrefLangLinks = document.querySelectorAll('link[hreflang]');

langLinks.forEach(function(langLink) {
  getLangLink(langLink)
})

function getLangLink(fnLangLink) {
    var langCode = fnLangLink.getAttribute("data-language-link")
  hrefLangLinks.forEach(function(hrefLangLink) {
    var hrefLangCode = hrefLangLink.hreflang.toLowerCase().substring(0, 2);
    if (hrefLangCode.includes(langCode)) {
      var hrefLangURL = hrefLangLink.href.toLowerCase();
      if (hrefLangURL.length > 21  // 23 is the length of the string https://www.occupop.io/
          && hrefLangURL[hrefLangURL.length -1] !== "/") {
        fnLangLink.href = hrefLangURL
      }
    }
  })
}