I have a tabbable image that I want to play a sound if it is tabbed to and enter is pressed. It's not a button for a form or anything, just an image. How can this be done?
<img src="/images/butt.gif" onclick="fartSound();" tabindex="0">
I already have Javascript where a sound is played when clicked, but I would really love it if I could also have the sound played when it is tabbed to and enter is pressed.
function fartSound(){
var sound = new Audio('/audio/fart.mp3');
sound.play();
};
Any ideas? Thanks!
You can listen to the focus event with javascript.
Something like element.addEventListener('focus', fartSound);
Just click on the white space and hit tab, you will see the console log.
function fartSound(){
console.log("Prrr");
var sound = new Audio('/audio/fart.mp3');
sound.play();
};
const funnyPic = document.getElementById('funnyPic');
funnyPic.addEventListener('focus', fartSound);
<img src="/images/butt.gif" tabindex="0" id="funnyPic">
Add addEventListeners for pressing(keydown) on 'enter'. and add onFocus event in HTML to call the function on click or tabbed
function fartSound(){
console.log('clicked');
var sound = new Audio('/audio/fart.mp3');
sound.play();
};
const element = document.getElementById('element');
element.addEventListener('keydown', function(e) {
//Enter key value is 13
if(e.which == 13) {
fartSound();
}
});
<img src="/images/butt.gif" onfocus="fartSound()" tabindex="0" id="element">