I have to handle with the behaviour of an audio element in an HTML page. The audio starts when the user arrives on the page. I'd like to not play it again if he reaches again the page during the same session. I tried that code but it does not work. Do you have some suggestion about it? thank you very much
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<audio controls autoplay class="hidden-xs" style=" position:fixed; right:0; bottom:0; z-index:99999999999">
<source src="music_bbms.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script>
$(document).ready(function() {
if (!localStorage.getItem('played') {
$('.music').attr('autoplay', false);
localStorage.setItem('played', true);
}
});
</script>
Here are some things I think might be wrong:
.music
on your audio element, so how can you change its attribute using that class selector. I have added an id to the audio element and used that id for selecting it. if
condition, I have fixed that. <audio id="music" controls class="hidden-xs" style=" position:fixed; right:0; bottom:0; z-index:99999999999">
<source src="music_bbms.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
<script>
$(document).ready(function() {
if ( sessionStorage.getItem('played') != "true" ) {
$('#music').get(0).play();
sessionStorage.setItem('played', "true");
}
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.