-2

Why the code is not working if I put script content before? But when I added script after Video Tag, it worked. Explain this plz

var vid = document.getElementById("myVideo");

function play(){
    vid.play();
}

function pause(){
    vid.pause();
}


</script>




<button onclick="play()">Play</button>
<button onclick="pause()">Pause</button>

<video id="myVideo">
    <source src="john.mp4" type="video/mp4">
</video>





</html>
Saim
  • 15
  • 1
  • 4

2 Answers2

1

The script is evaluated according to its location. You are trying to access html that was not rendered, yet.

You can put it before, but use document ready event.

Yaniv Efraim
  • 6,200
  • 6
  • 48
  • 92
0

Cuz the browser interpret the code line by line. If you want to find a html tag with javascript which does not exist yet it obviously wont find it and this is the case in your code if you put the video tag after the script tag. If you really want to put your script before the html tags you can force the javascript to only run after the full dom is loaded. Like with:

window.onload = function() {
    //your script here
};

Or with jquery document ready function. Or with putting your script to external file and call it with defer html script attribute like

 <script src="yourScript.js" defer></script>
kailniris
  • 6,530
  • 1
  • 14
  • 22