I constructed some HTML and JavaScript code for a video player. It plays the video, but when I press pause, then press play again the play count increases. I only want the play count to increase after the song has finished playing. Below is the java script format. If HTML code is needed I will provide it. I'm just having trouble meeting the post requirements. I'm being told that I'm writing too much code. It is a simple video player though.
<script>
// JavaScript
const videoPlayer = document.querySelector('.video-player');
const videoElement = videoPlayer.querySelector('.video');
const playCountElement = videoPlayer.querySelector('.play-count');
let playCount = 0;
function updatePlayCount() {
playCountElement.textContent = playCount + ' Plays';
}
function savePlayCount() {
localStorage.setItem('playCount', playCount);
}
function loadPlayCount() {
const storedPlayCount = localStorage.getItem('playCount');
if (storedPlayCount !== null) {
playCount = parseInt(storedPlayCount);
}
}
function playVideo() {
videoElement.play();
playCount++;
updatePlayCount();
savePlayCount();
}
function pauseVideo() {
videoElement.pause();
}
function togglePlayPause() {
if (videoElement.paused) {
playVideo();
} else {
pauseVideo();
}
}
videoElement.addEventListener('ended', function () {
videoElement.currentTime = 0; // Reset video to the beginning when it ends
hasBeenPlayed = false; // Set hasBeenPlayed to false only when you want to reset play count after the video ends
pauseVideo();
});
videoElement.addEventListener('play', function () {
playCount++; // Increment play count when video starts playing
updatePlayCount();
savePlayCount();
});
videoPlayer.addEventListener('click', togglePlayPause);
// Load the initial play count when the page loads
window.addEventListener('load', function () {
loadPlayCount();
updatePlayCount();
});
</script>
Try having a variable to note if it's a "first time playing" as...
(1) Replace
let playCount = 0;with the following:Playing a video should update
playCountonly during the first play.(eg: future pauses will skip the "IF" code):
(2) Replace function
playVideo()code with this new version: