skip to Main Content

I have a few videos on my html site and I want them to be showen with a poster (thumbnail). The controls should only be visible when the user clicks on the video for the first time. So when the user visits the page, the controls should be hidden an when the user clicks on the video the controls should be visible.

This is the js I tried (is in the header tag):

<script>
      document.getElementById("video1").addEventListener("click", setAttribute("controls", "true"));
    </script>

And this is my html:

<div class="container1">
  <video src="Videos/Film 1.mp4" poster="Thumbnails/Film 1.jpg" class="video1" id="video1"> 
  </video>
</div>

2

Answers


  1. You have used the callback function of event listener wrong. Thats why it was not working

    Also you need to place your script in end of html body.

    <div class="container1">
      <video src="http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4" poster="Thumbnails/Film 1.jpg" class="video1" id="video1"> 
      </video>
    </div>
    <script>
    const videoElement = document.getElementById("video1");
    videoElement.removeAttribute("controls");
        videoElement.addEventListener("click", () => {
        videoElement.setAttribute("controls", "true");
        videoElement.play();
     });
        </script>
    Login or Signup to reply.
  2. The method setAttribute is not a part of Window object. It is a part of a specified element.

    https://developer.mozilla.org/en-US/docs/Web/API/Element/setAttribute

    You have to select the element using geElementById/geElementsByClassName or etc..

    In this case, You can get element from event.target since you want to select the element which is the origin of the event.

    document.getElementById("video1").addEventListener(
        "click",
        (event) => event.target.setAttribute("controls", "true")
    );
    .video1 {
      background-color: rgb(200,200,200);
    }
    <div class="container1">
      <video src="Videos/Film 1.mp4" poster="Thumbnails/Film 1.jpg" class="video1" id="video1"> 
      </video>
    </div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search