I have a custom audio seek bar I would like to make it clickable and make the audio jump to that section. This is my HTML code of the audio seek bar
<audio src="" preload="auto" controls id="audioPlayer" ontimeupdate="updateTrackTime(this);" style="width: 0px; visibility: hidden ;"></audio>
<div class="p-bar">
<div class="progress1" id="progress1"></div>
</div>
This is my CSS code:
.p-bar{
flex: ;
width: 25%;
height: 4px;
background: #333333;
}
.progress1 {
height:3px;
background: whitesmoke;
transition: width .1s linear;
cursor: pointer;
justify-self: left;
left: 0;
box-shadow: 1px 1px 2px white;
}
This is my JavaScript code of the seek bar:
var track = document.getElementById('audioPlayer');
var controlBtn = document.getElementById('play-pause');
var timer;
var percent = 0;
var audio = document.getElementById("audioPlayer");
audio.addEventListener("playing", function(_event) {
var duration = _event.target.duration;
advance(duration, audio);
});
audio.addEventListener("pause", function(_event) {
clearTimeout(timer);
});
var advance = function(duration, element) {
var progress = document.getElementById("progress1");
increment = 10/duration
percent = Math.min(increment * element.currentTime * 10, 100);
progress.style.width = percent+'%'
startTimer(duration, element);
}
var startTimer = function(duration, element){
if(percent < 100) {
timer = setTimeout(function (){advance(duration, element)}, 100);
}
}
You can make any HTML element clickable by using a "click" event handler. Once you're inside the click event handler, the MouseEvent passed to the handler will have about five different ways to get the x position of the mouse click, so you can determine how far left on the bar the user clicked. You may need to try a few of them to see which works for you, but I'd suggest starting with offsetX. From there you should be able to calculate the percentage to skip the media to based on the percentage along the progress item the user clicked.