Script stops working when using variables to save time typing...

Joined
Oct 31, 2022
Messages
3
Reaction score
0
Hi, I am starting with HTML, CSS and JavaScript. I got an exercise where I have to create a button that will play or pause a video depending of its status. The thing is that if I make a var with the getelement to save time and dont need to type so much, it just stops working, and I dont understand why.
Basically, if I write like this, it works:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Opdracht 9-6.</title>
<script type="text/javascript">
function play(){
if(document.getElementById("video1").paused){
document.getElementById("video1").play();
}
else{
document.getElementById("video1").pause();
}
}
</script>
</head>
<body>
<button type="button" onclick="play()">Play</button>
<br>
<video id="video1">
<source src="video/clickbait.webm">
</video>

</body>
</html>

BUUUUUUT, if I write it like this, should be the same, but it doesnt work:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Opdracht 9-6.</title>
<script type="text/javascript">
var mivideo=document.getElementById("video1");
function play(){
if(mivideo.paused){
mivideo.play();
}
else{
mivideo.pause();
}
}
</script>
</head>
<body>
<button type="button" onclick="play()">Play</button>
<br>
<video id="video1">
<source src="video/clickbait.webm">
</video>

</body>
</html>

What am I doing wrong? t.t
 
Joined
Jul 3, 2022
Messages
93
Reaction score
23
JavaScript:
var mivideo=document.getElementById("video1");

This element doesn't exist at that moment yet
 
Joined
Mar 11, 2022
Messages
227
Reaction score
32
You may use body.onload event or something like this
Code:
var mivideo=false;
function play(){
if(!mivideo){
if(document.getElementById("video1")){mivideo=document.getElementById("video1");}
}
if(mivideo){
if(mivideo.paused){
 mivideo.play();
 }
 else{
 mivideo.pause();
}
}
}
 
Joined
Oct 31, 2022
Messages
3
Reaction score
0
You may use body.onload event or something like this
Code:
var mivideo=false;
function play(){
if(!mivideo){
if(document.getElementById("video1")){mivideo=document.getElementById("video1");}
}
if(mivideo){
if(mivideo.paused){
 mivideo.play();
 }
 else{
 mivideo.pause();
}
}
}
It worked ! Thanks!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,059
Latest member
cryptoseoagencies

Latest Threads

Top