Code snippet: Saying hello in multiple languages

17 June 2020

I have the following greeting on my homepage which switches between multiple languages:

Hello!
I'm Ed.

It always starts “Hello”, then “Bonjour”, and then into the random cycle.

Feel free to steal this snippet, and add your own greetings:

<h1>
  <span id="hello">Hello!</span><br>
  I'm Ed.
</h1>
#hello {
  transition: opacity 125ms linear;
}
function getShuffledGreetings(){
  var greetings = [
    "Guten tag!", "Salām!", "Hola!", "こんにちは",
    "Hej!", "Ciao!", "你好", "Merhaba!", "नमस्ते"
  ]

  // Shuffle the array
  greetings = greetings.slice().sort(function(a, b){
    return 0.5 - Math.random()
  });

  // Ensure first greeting of cycle is "Bonjour!"
  greetings.unshift("Bonjour!");

  // Ensure last greeting of cycle is "Hello!"
  greetings.push("Hello!");

  return greetings;
}

document.addEventListener("DOMContentLoaded", function(){
  var element = document.getElementById('hello');
  var shuffledGreetings = getShuffledGreetings();

  setInterval(function(){
    if (shuffledGreetings.length === 0)
      shuffledGreetings = getShuffledGreetings();

    element.style.opacity = "0";
    setTimeout(function(){
      element.textContent = shuffledGreetings.shift();
      element.style.opacity = "1";
    }, 150); // 150ms -- slightly more than the opacity transition
  }, 2000); // update the greeting every 2 seconds
});

Any questions or suggestions? Please feel free to get in touch -- ed@edforshaw.co.uk