Pause the YouTube video and swap it out with an image

I am currently working on incorporating an embedded YouTube video into my project. I want to replace the video with an image, and when the image is clicked, the video should start playing. I have successfully implemented this functionality:

<script type="text/javascript>
   function start_video() {
      var iframe = '<iframe title="YouTube video player" width="590" height="360" src="http://www.youtube.com/embed/nCgQDjiotG0?autoplay=1&amp;rel=0&showinfo=0" frameborder="0" title="none" allowfullscreen></iframe>';
      document.getElementById("video_player").innerHTML = iframe;
   }
</script>

Here is the HTML code:

<div id="video_player"><img style="cursor: pointer;" onclick="start_video();" src="fake_image.jpg" alt="Play Video" /></div>

However, I am now facing a challenge in stopping the video playback by clicking on another div or element while simultaneously replacing the video with the original image.

Answer №1

My recommendation is to delve into the Javascript Youtube API. It provides much greater control compared to simply embedding an iframe on your website.

Answer №2

Is there a way to replace the iframe with an image by giving it an id?

function stop_video() {
    var elem = document.getElementById('video_iframe');
    var parent = elem.parentNode;
    parent.removeChild(elem);
    var image = document.createElement('img');
    image.setAttribute('src','yourImage.jpg');
    parent.appendChild(image);
}

It's recommended not to set innerHTML, but rather handle objects like in the function above.

function start_video() {
    var iframe = document.createElement('iframe');
    iframe.setAttribute('title','Youtube video player');
    iframe.setAttribute('width','590');
    iframe.setAttribute('height','360');
    iframe.setAttribute('src','http://www.youtube.com/embed/nCgQDjiotG0?autoplay=1&amp;rel=0&showinfo=0');
    iframe.setAttribute('frameborder','0');
    iframe.setAttribute('allowfullscreen','allowfullscreen');
    document.getElementById('video_player').appendChild(iframe);
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to implement a scrollbar within a DIV element?

I'm working on a webpage that includes several customized buttons within multiple DIVs. Take a look at this example on the fiddle. Since I have a lot of buttons, I need to find a way to add a scrollbar so users can easily navigate to the desired butt ...

Embedding JavaScript directly into a Jade file(Note: This is

After spending about 3 hours trying to unravel the mystery, I'm still lost and unsure where to even begin looking for answers. We implemented a method that allows us to include JS files directly in a single Jade file, serving as a manifest for all ou ...

Module Ionic not found

When I attempt to run the command "ionic info", an error is displayed: [ERROR] Error loading @ionic/react package.json: Error: Cannot find module '@ionic/react/package' Below is the output of my ionic info: C:\Users\MyPC>ionic i ...

Guide on transferring data from a component to App.vue in Vue 3, even with a router-view in the mix

I have the following layout: src components Footer.vue views Page.vue App.vue I want to access the 'message' vari ...

Unable to adjust layout when code is functioning alongside background-color

I'm looking to dynamically change the position of an item on my webpage when it is clicked. Is there a way I can achieve this without relying on id names? I currently have a code snippet that successfully changes the background color, but for some rea ...

Revise the JSON format to be compatible with a JavaScript template library

My goal is to utilize JSON data for parsing a template using JavaScript. The Mustache library provides a solution as shown below: var output = $("#output"); // template stored in JS var as a string var templateString = '<div>'+ '< ...

What might be causing my image element in JavaScript to be unable to load a path (src) from an array?

I'm trying to create a slideshow, but I'm having trouble getting the image element to pick up the source from a script. When I hardcode the source in the img element, it works fine. However, when I store the path in an array and try to load it us ...

What does the concept of hydration entail when working with React?

Recently, I've been delving into the world of React and stumbled upon the concept of hydration. Unfortunately, I'm a bit confused about how it operates. Can anyone provide some insights? Thank you in advance. While working on my React app, I enc ...

Merging two separate observableArray into a single entity in knockout js

I am currently working on merging two distinct arrays into a general array and then connecting it using foreach. My View Model: self.cancelledItem1 = ko.computed(function () { return ko.utils.arrayFilter(self.items(), function (item) { ...

Why am I experiencing varying outcomes between createShadowRoot and attachShadow methods?

Recently, I've encountered an issue related to shadow dom while working on a project. After referring to an older tutorial that uses createshadowroot, I realized that this method is now considered deprecated and should be replaced by attachshadow. Un ...

"Facing internal server error while using jQuery ajax post method for making a request

$("[id$=_btnPostReminder]").click(function(){ var a = $find("<%=Editor1.ClientID%>"); var remindertext = a.get_content(); var re=$("#<%=hiddReminderTicketId.ClientID%>").text(); var res= $("#<%=txtReminderon.ClientID%> ...

What is the best way to send data to a component through a slot?

Currently, I am working on a Vue application that utilizes pimcore and twig in the backend. My task involves creating a component that can receive another component (slot) and dynamically render it with props. Here is the root structure found in viani.twig ...

Learning how to interpret jsonpickle data within an Angular TypeScript file

I am currently developing a hobby application that uses Angular for the front-end and Python for the back-end. In this setup, a component in Angular sends an HTTP GET request to Python, which responds with a jsonpickled object. My goal is to decode the js ...

Alter the reply prior to being dispatched to the customer

Node 16.14.2, Express 4.18.1 There have been several instances where individuals have altered res.send in order to execute actions before the response is sent to the client. app.use(function (req, res, next) { originalSend = res.send; res.send = f ...

What are the best techniques for positioning text next to images in HTML and CSS?

I have attempted to position the text in close proximity to the images as shown in the picture below (to allow for spacing in the middle). As depicted in the image, the "AVENUE FOR GROWTH" and "NETWORKING OPPORTUNITIES" texts are near Man's hand and w ...

Is it possible for Sequelize to utilize a getter or setter within a find query?

When it comes to storing and querying email addresses in my database, I always opt for lowercase strings to prevent duplicate emails such as <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="077274627547627f666a776b62d48ed88e5"> ...

Place the moving square at the center and bottom of the screen

Can anyone help me figure out how to center and place the red box at the bottom of the orange div? The size of the red box varies from one box to another, both in height and width. This positioning needs to be compatible with all browsers, including Inte ...

Building CSS Using TagBuilder in .NET Core

Can you provide guidance on utilizing the Tag Builder CSS Class? I am interested in integrating it into a style class .custom-image { max-width: 100%; max-height: 100%; padding: 0; background-color: white; } TagBuilder image = new TagBuilder("img"); Wh ...

Exploring the Power of Modules in NestJS

Having trouble with this error - anyone know why? [Nest] 556 - 2020-06-10 18:52:55 [ExceptionHandler] Nest can't resolve dependencies of the JwtService (?). Check that JWT_MODULE_OPTIONS at index [0] is available in the JwtModule context. Possib ...

How can I set up a session in order to fetch information from a MySQL table

Can you guide me on implementing this session: (UserID is part of the login table) Session["UserID"]="usrName"; How can I incorporate the above code into the following script? using System; using System.Data; using System.Collections.Generic; using Sys ...