Im trying to create an audio preview page on my webpage where each audio element has its own progress bar. Im having trouble however, getting each audio element to target only its progress bar. I am pretty new to this, so I hope this isn't too much a straight forward dumb question, but I'd really appreciate the help, Thanks in advance.
This is the html for each song preview.
<audio id="player"></audio>
<div class="songPreview">
<div class="disp">
<div class="button" data-src="EXAMPLE.wav" data-pos="0">
<a href="#" class="soundPlay"><img src="Buttons/play.png"></a>
<a href="#" class="soundStop hidden"><img src="Buttons/stop.png"></a>
</div>
<div class="songInfo">
<p>SONG NAME HERE</p>
</div>
</div>
<progress class="seekbar" value="0" max="1" style="width:250px"></progress>
</div>
<div class="songPreview2">
<div class="disp">
<div class="button" data-src="EXAMPLE2.wav" data-pos="0">
<a href="#" class="soundPlay"><img src="Buttons/play.png"></a>
<a href="#" class="soundStop hidden"><img src="Buttons/stop.png"></a>
</div>
<div class="songInfo">
<p>SONG NAME HERE</p>
</div>
</div>
<progress class="seekbar" value="0" max="1" style="width:250px"></progress>
</div>
and this is the JS
$(document).ready(function() {
var myAudio = document.getElementById("player");
//play stop button etc.
$(document).on('click', '.soundPlay', function(e) {
var target = this;
$(this).hide();
$(this).next("a").show();
myAudio.src = target.parentNode.getAttribute('data-src');
myAudio.play();
e.preventDefault();
});
$(document).on('click', '.soundStop', function(e) {
var target = this;
$(this).hide();
$(this).prev("a").show();
$('audio').each(function(){
this.pause();
this.currentTime = 0;
});
e.preventDefault();
});
//end of play stop button
//seekbar
$('#player').on('timeupdate', function() {
$('.seekbar').attr("value", this.currentTime / this.duration);
});
//end seek bar
//auto switch button on stop
var audio = document.getElementById('player');
audio.addEventListener('ended', stopAudio);
function stopAudio() {
audio.stop;
$('.soundPlay').show('slow');
$('.soundStop').hide('fast');
$('.seekbar').attr(this.currentTime = 0);
}
});
I just cant seem to figure out how to target only the progress tag in each respective div. Is there anyway I can do this without a million different progress IDs and overly repetitive JS code? ( because there's gonna be like 100 of those song previews on a page )
Thanks in advance!
You have to track the current sound div
being played - with the data-src
.
Use .val()
instead of attr('value')
Try this,
$('#player').on('timeupdate', function() {
$('div[data-src="'+this.src+'"]').parents('.disp').siblings('.seekbar').val(this.currentTime / this.duration);
});
Also,
Change stopAudio()
to this
function stopAudio() {
audio.pause();
audio.currentTime = 0;
$('.soundPlay').show('slow');
$('.soundStop').hide('fast');
$('.seekbar').val(0);
}