JavaScript30 - Day 23

By Camilla Krag Jensen naxoc |

Day 23 of #javascript30 is having fun with speech synthesis and new tricks for passing arguments to a callback function.

Speech synthesis in the browser

I could not make the lesson example work with the voices dropdown in Firefox. I like Firefox and I have recently switched back to using it as my default browser. I switch back and forth at least a couple of times every year. I even blog about it sometimes. Anyway. To make it work in Firefox (and Chrome), I did this:

function populateVoices() {
  voices = speechSynthesis.getVoices();
  voicesDropdown.innerHTML = voices
    .map(voice => `<option value="${voice.name}">${voice.name} (${voice.lang})</option>`)
    .join('');
}
if (speechSynthesis.onvoiceschanged !== undefined) {
  speechSynthesis.onvoiceschanged = populateVoices;
}

instead of using an event listener like this:

speechSynthesis.addEventListener('voiceschanged', populateVoices);

I kinda stole it from the MDN docs for SpeechSynthesis.

Passing arguments to a callback function

I also learned some new tricks when it comes to passing arguments to a callback function in JavaScript. I made a pen with them:

See the Pen Passing arguments to a callback function by Camilla Krag Jensen (@naxoc) on CodePen.

Not only will the first one not work. It will set the text "I should be an animal" to "nope" when then page loads. Try commenting out the last line where I set textDiv.textContent. I guess you can say it works once - just not the way you want it to :)