How do I play a song when the user puts the mouse over an element?

3

Is it possible that when the user hover over a certain element on the site, a song would play? If so, how?

    
asked by anonymous 07.10.2017 / 23:41

2 answers

8

You can combine onmouseover with element <audio> :

var x = document.getElementById("musica"); 

function mouseOver() { 
    x.play(); 
} 
<audio id="musica">
  <source src="https://www.w3schools.com/html/horse.mp3"type="audio/mpeg">
</audio>
<h1 onmouseover="mouseOver()">Iniciar musica</h1>
    
08.10.2017 / 00:11
3

With Play and Pause:

var x = document.getElementById("myAudio"); 

function playAudio() { 
    x.play(); 
} 

function pauseAudio() { 
    x.pause(); 
} 
<audio id="myAudio">
  <source src="http://musicasitalianas.com/fileMP3/innobra.mp3"type="audio/mpeg">
  <source src="" type="audio/ogg">
  Seu browser não suporta audio.
</audio>

<image src="http://kithomepage.com/images/Play-Normal-icon.png"width="64" height="64" onmouseover="playAudio()">
<image src="http://kithomepage.com/images/Pause-Normal-icon.png"width="64" height="64"onmouseover="pauseAudio()"> 
  

Font

With controls

var x = document.getElementById("myAudio");
x.controls = false;
function reproduzir() { 
    x.controls = true;
    x.load();
    x.play();
    document.getElementById('img').style.display = 'none';
} 
<audio id="myAudio" controls>
  <source src="" type="audio/ogg">
  <source src="http://musicasitalianas.com/fileMP3/innobra.mp3"type="audio/mpeg">
  Seu browser não suporta audio.
</audio>

<image id="img" src="http://kithomepage.com/images/Play-Normal-icon.png"width="32" height="32" onmouseover="reproduzir()">
    
08.10.2017 / 01:22