I am using javaScript to handle play and pause button when user click on play pause button, but it is not working in my case it throw following error in my console when click on play buttonUncaught TypeError: Cannot read
properties of null (reading 'addEventListener')
at myMusic.js:46:12
Here is my handle play pause function
let audioElement = new Audio('song/Si Tu Te Vas.mp3');
let masterPlay = document.getElementById('masterPlay');
/**Handle play pause click*/
masterPlay.addEventListener('click', () => {
if (audioElement.pause() || audioElement.currentTime <= 0) {
audioElement.play();
masterPlay.classList.remove('fa-play-circle');
masterPlay.classList.add('fa-pause-circle');
gif.style.opacity = 1;
} else {
audioElement.pause();
masterPlay.classList.remove('fa-pause-circle');
masterPlay.classList.add('fa-play-circle');
gif.style.opacity = 0;
}
})
Mymusic.html
<script type="text/javascript" th:src="@{/js/myMusic.js}"></script>
<div class="icons">
<!--Font awsome icon -->
<i class="fas fa-3x fa-backward" id="previous"></i>
<i class="far fa-3x fa-play-circle" id="masterPlay"></i>
<i class="fas fa-3x fa-forward" id="next"></i>
</div>
Place the <script>
tag after the <div class="icons">
Scripts cannot get DOM content loaded after it
Or you could wrap your javascript in:
window.addEventListener('DOMContentLoaded', () => {
// Your code here
})
To wait for the DOM content all loaded in before the script :)