0

At this moment I'm quite frustrated. I want to control a video via javascript:

  • set the volume to 20%
  • play & pause by clicking the video

That for I have this html (which also includes a little php)

<head>
<link rel="stylesheet" type="text/css" href="style.css">
<script src="player.js" type="text/javascript"></script>
</head>
<body>
<?php
        if(isset($_GET["id"])) {
                $video = $_GET["id"];
        }else{
                $video = "test.mp4";
        }
?>

<video id="video" preload="auto" autoplay="true"  loop="loop">
     <?php echo "<source src=\"$video\" type=\"video/mp4\">"; ?>
     <source src="movie.webm" type="video/webm">
          Sorry, your browser does not support HTML5 video.
</video>
</body>

player.js:

var vid = document.getElementById('video');

vid.volume = 0.2;

vid.addEventListener('click', function () {
        if (vid.paused == false) {
            vid.pause();
            vid.firstChild.nodeValue = 'Play';
        } else {
            vid.play();
            vid.firstChild.nodeValue = 'Pause';
        }
});

But Chromes console's just showing: Uncaught TypeError: Cannot set property 'volume' of null Why is that? Thanks in advance!

lemon
  • 17
  • 9
  • 1
    At the time your script runs, the video element hasn't been seen yet so it's not part of the DOM. Move your ` – Pointy Feb 05 '18 at 18:56
  • 1
    **Danger**: This code is [vulnerable to XSS](https://www.owasp.org/index.php/XSS) User input needs escaping before being inserted into an HTML document!. – Quentin Feb 05 '18 at 19:04

1 Answers1

1

You should move the script tag at the end of body tag, currently your DOM hasn't been set when the script loads, hence it can't access elements from DOM.

Aaditya Thakkar
  • 1,296
  • 6
  • 13