ZeWorks
ZeWorks

Reputation: 87

what does this javascript logic mean?

I can't wrap my head around this code from w3schools for a javascript play/pause event.

let video = document.getElementById("myVideo");
let btn = document.getElementById("myBtn");

function myFunc() {
	if (video.paused) {
    	video.play();
        btn.innerHTML = "Pause";
    } else {
    	video.pause();
        btn.innerHTML = "Play";
    }
}

if the video paused is true then the video should play and the btn should display Pause. But shouldn't it be the other way round? If the video is paused then video.pause() should be there?

Upvotes: -1

Views: 38

Answers (1)

Script47
Script47

Reputation: 14550

Remember, the action is performed when you click the button, so imagine if the video is playing and the function is executed, then the following snippet runs:

video.pause(); // the played video is now paused
btn.innerHTML = "Play"; // the button now shows 'Play' from what it was before 'Pause'

When the function is executed again (when it is paused) the code checks if it is paused and if it is then it means it needs to play hence the following snippet:

if (video.paused) { // Was the video paused? If yes...
    video.play(); // We now play the video as it was paused
    btn.innerHTML = "Pause"; // We changed the button text from 'Play' to 'Pause'
}

The comments in the above snippets should clarify further.

Upvotes: 1

Related Questions