Iframe backgound image

I want to embed video from youtube on my site, but I want it to have another image ,not the one from youtube. How to do that ,I tried with simple background image on iframe tag , it doesn’t work?

I don’t really know much about youtube videos but I believe to do it properly you would probably need the youtube API and would be a question for the JS forum.

If you just wanted an initial image over the iframe you could fake it like this:

However the video won’t start until you click play so you are probably stuck at using the API from youtube which I think you have to sign up to to get an API key (although I may be mistaken as I don’t really know much about youtube videos).

2 Likes

Add the following to your function:

document.querySelector(“iframe”).src += “?autoplay=1”;

2 Likes

A similar approach would be to use an absolutely positioned <img> element as a foreground image:

CSS

img {
  position: absolute;
  cursor: pointer;
  opacity: 0.9;
  transition: 1s;
}

iframe {
  border: 0;
}

.active {
  opacity: 0;
  pointer-events: none;
}

HTML

<img src="https://i.stack.imgur.com/rET57.jpg" alt="Foreground image">

<iframe width="500" height="300" src="https://www.youtube.com/embed/ScMzIvxBSi4" title="YouTube video player" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>

JavaScript

document.querySelector('img').addEventListener('click', function() {
  this.className = 'active';
  document.querySelector('iframe').src += '?autoplay=1';
});

DEMO
(Neither CodePen nor JSFiddle seems to allow YouTube videos autoplay, so I had to use an independent web page.)

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.