Search code examples
javascriptonmouseover

Play song at onmouseover and stop song at onmouseout


I am working on a onmouseover to play a song for a school project. I already found code for onmouseover and onmouseout but with Alerts its still not working.

If you can help me it would be great. Many thanks!

document.getElementById("RockButton").onmouseover = function() {
   mouseOver()
};
 document.getElementById("RockButton").onmouseout = function() {
   mouseOut()
};

function mouseOver() {
   alert('Hello out there!')
}
function mouseOut() {
   alert('Hello out there!')
}

<div id="PaginaDrieTatjana" style="display:none;">
  <h1>Kies soort dans</h1>

  <div id="Rock">
    <h3>Rock Dance</h3>
    <img src="Tatjana/Een.jpg" style="width: 100%;">
    <div id="RockButton">
        <p>Kiezen</p>
    </div>
  </div >

  <div id="Pop">
    <h3>Pop Dance</h3>
    <img src="Tatjana/Twee.jpg" style="width: 100%;">
    <div id="PopButton">
        <p>Kiezen</p>
    </div>

  </div>

Solution

  • use jquery for simplify things, define class for the button and get audio tag element attributes to play or pause.

    <div id="Rock">
         <h3>Rock Dance</h3> 
        <img src="Tatjana/Een.jpg" style="width: 100%;">
        <div class="Button">
            <p>Kiezen</p>
            <audio id="RockDanceAudio" src="rock_audio.mp3"></audio>
        </div>
    </div>
    <div id="POP">
         <h3>Rock Dance</h3> 
        <img src="Tatjana/Een.jpg" style="width: 100%;">
        <div class="Button">
            <p>ROFL</p>
            <audio id="PopDanceAudio" src="pop_audio.mp3"></audio>
        </div>
    </div>
    

    and use this script

    $('.Button').mouseover(function () {
        $audio_tag_id = $(this).find('audio').attr('id');
        document.getElementById($audio_tag_id).play();
    });
    $('.Button').mouseout(function () {
        $audio_tag_id = $(this).find('audio').attr('id');
        document.getElementById($audio_tag_id).pause();
    });
    

    it will work for n number of buttons, happy coding :)