beck5 beck5 - 6 months ago 12
HTML Question

audio controls appear on mouseover and fade away on mouseout

what I want to do is make audio controls be visible on page load, fade out after 5 seconds, appear on hover/mouseover and fade out 5 seconds after mouse out. exactly like the youtube control bar works.

Thanks in advanced.



<audio controls>
<source src="horse.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>




Answer

$(document).ready(function(){
   $('#audio-placeholder').hover(
       function(){
         //runs on mouseover
         $('#audio-controls').fadeIn();
       },
       function(){
         //runs on mouseout
         hideAudioControls(); 
       }
   );
  hideAudioControls(); //runs at startup
});

function hideAudioControls(){
   setTimeout(function(){
     $('#audio-controls').fadeOut();
   },3000);
}
div{position:relative;}
.audio-inner{position:absolute;top:0;left:0;}
#audio-controls{background:white;z-index:1;}
#audio-placeholder{width:300px;height:20px;padding-top:10px;text-align:center;z-index:0;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="audio-container">
  <div id="audio-controls" class="audio-inner">
    <audio controls>
      <source src="horse.mp3" type="audio/mpeg">
       Your browser does not support the audio element.
    </audio>
  </div>
  <div id="audio-placeholder" class="audio-inner">
     Hover here for controls
  </div>
</div>

Notes:

Basically, there is one box (audio-container) that contains two other boxes.

The audio-container box must be styled position:relative for the position:absolute to work in the other two boxes. position-absolute makes the two boxes go one on top of the other, so I also used z-index to tell it which box is on top (z-index:1) and which is on bottom (z-index:0) Note that you can make up any number for z-index - the bigger number is on top of the lower number.

hover() takes two functions - the first fires on mouseover, and the second fires on mouseout.

The javascript code uses jQuery, so you must reference it in your document (as done in the example code.)