How to make it play a song when the user puts the mouse on top of an element?

Asked

Viewed 935 times

3

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

2 answers

8


You can combine the onmouseover with the 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>

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()"> 

Source

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()">

Browser other questions tagged

You are not signed in. Login or sign up in order to post.