Accessing DOM using Javascript

I am trying to build an interactive video player, but I am not able to access the DOM elements using Javascript. Here’s my Javascript code in assets.

Preformatted text

var vid =  document.getElementById("video-display");
var bar =  document.getElementById("bar");

vid.addEventListener('click',play, false);
bar.addEventListener('click',update, false);
bar.addEventListener('click',seek, false);


function play() {
if(vid.paused) { vid.play(); } else { vid.pause(); }
};

function update() {
var pct = vid.currentTime/vid.duration*100;
bar.style.background = "linear-gradient(to right, #500 "+pct+"%, #000 "+pct+"%)";
};

function search() {
  coords = bar.getBoundingClientRect()
  var s = document.createElement("span");
  s.style.left = ((895/vid.duration*vid.offsetWidth-2)/vid.offsetWidth)*100+"%";
  bar.appendChild(s);
};


function seek(e) {
coords = bar.getBoundingClientRect()
vid.currentTime = ((e.pageX-coords.x)*(vid.duration/vid.offsetWidth));
console.log((e.pageX-coords.x)*(vid.duration/vid.offsetWidth),"check")
if(vid.paused) { vid.play(); }
};

search();

I am getting error-
Uncaught TypeError: Cannot read property ‘addEventListener’ of null at vid.addEventListener(‘click’,play, false);

I had encountered the same issue as you did, i.e. variables having null values. Apparently this can arise when the script is called and the layout is not totally rendered. The following topic helped me solve the issue :

Not actually answering your question here, but you might consider writing a custom component for your video player:

https://dash.plotly.com/plugins

It would in principle be much more portable, plus you can share with the community. :slight_smile: