HTML element DIV positioned above the iframe

I am looking for a way to automatically place a "PLAY" div above each iframe instead of doing it manually.

I have successfully done it manually but I'm not sure how to achieve the same result with a script or using CSS.

Below is my HTML markup:

<ul data-role="listview" id="resultat"></ul>

And here is the Javascript code I am using:

$('#resultat').append('<li class="liste" ><iframe id="ytplayer" type="text/html" width="140" height="100" src="http://www.youtube.com/embed/RD98kNOBrNs?hd=1&rel=0&autohide=1&showinfo=0&wmode=opaque" frameborder="0"/></li>').listview("refresh");

Currently, I am positioning the div above the iframe manually using z-index and position attributes. However, I don't believe this is the best approach for automating the process.

Any suggestions or solutions would be greatly appreciated. Thank you.

Answer №1

In addition to Matyas' response, I have made some modifications to his code to ensure it can be fully implemented. Before delving into the details, please check out the demo:

VIEW DEMO CODE HERE

As you can observe, I dynamically set the widths and heights so that the overlayDiv is perfectly centered within the iFrame. Feel free to adjust the width and height of the overlayDiv as needed, and the script will automatically adapt the start button's position.

It's crucial to maintain the following HTML structure for successful implementation:

<div id="vidFrame" class="play">
 <iframe id="video" class="youtube-player" type="text/html" width="520" height="330" src="http://www.youtube.com/embed/-PZLM-CmuJ0?wmode=opaque&hd=1&rel=0&autohide=1&showinfo=0&enablejsapi=1" frameborder="0"></iframe>
</div>

<div class="overlayDiv">
    <img src="https://www.ameliaconcours.org/UploadedContent/Lamborghini%20Logo_Crest_4C_S.png" alt="facebook" width="90px" />
</div>  

The width and height of vidFrame do not need to be predefined since they will match the iFrame's dimensions.

Additionally, pay attention to these specifics:

  • wmode=opaque should be the first parameter in the video URL
  • We enable enablejsapi=1 to control video playback

The jQuery function used is as follows:

$.fn.loadOverlay = function() {
    $('iframe').each(function(idx, iframe){     
        var imageHeight = $('.overlayDiv').height();
        var imageWidth = $('.overlayDiv').width();
        var marginTop = $('#video').height();
        var marginTop = marginTop/2-imageHeight/2;    
        var marginLeft = $('#video').width();
        var marginLeft = marginLeft/2-imageWidth/2;     
        
        $('.overlayDiv')                      
        .clone()                           
        .appendTo('body')                  
        .css({                              
            top: marginTop,      
            left: marginLeft,
        }).show();                        
    });
}

While lengthy, this calculation explicitly centers the overlay within the iFrame. Shorter methods are feasible, but this one provides clarity on the process.

Moreover, note that yt players typically display a red play button at the center when loading a video.

To remove this button, utilize the following trick:

function onPlayerReady(event){
        //THIS IS THE TRICK THAT YOU MIGHT WANT TO REMOVE
        player.playVideo();
        player.pauseVideo();
}

This method involves playing and immediately pausing the video to eliminate the button. However, please be aware that this technique does not function on mobile devices. It does offer the benefit of initiating video buffering automatically, enhancing user experience.

Lastly, the jsFiddle example is self-explanatory, so take your time to review and grasp the concept.

I trust this addresses your query. Best of luck!

Answer №2

$('iframe').each(function(idx, iframe){   // loop through each iframe
    var $iframe = $(iframe);              // create a jQuery reference for the current iframe
    $('.overlayDiv')                      // select the overlay template to place over each iframe
       .clone()                           // make a copy of it
       .appendTo('body')                  // add it to the end of the page
       .css({                             // set the dimensions and position of the overlay 
          top: $iframe.offset().top,      // position above the iframe
          left: $iframe.offset().left,
          height: $iframe.height(),
          width: $iframe.width(),
       }).show();                         // display the hidden overlay
});

Before implementation, ensure your .overlayDiv has these initial styles:

.overlayDiv {
    position: absolute;   /* placed above the iframe using javascript positioning */
    display: none;        /* hide the master template initially */
    z-index: 4953;        /* ensure the overlay appears on top of other elements */
}

This code hasn't been tested yet, but I wrote it while my build was running. You may need to adjust the positioning as needed.

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

Deleting entries from a selection of items in a list generated from an auto-fill textbox

I have successfully implemented an auto-complete Textbox along with a styled div underneath it. When the client selects an item from the Textbox, it appears in the div after applying CSS styling. Now, I am looking to create an event where clicking on the s ...

``The Vue.js routing system is determined by the incoming data received

Working with VueRouter to navigate to a component based on payload. { path: '/foobar', name: 'foobar', component: foobar, } { path: '/foobar', name: 'foobarSuccess', component: foobarSuccess, query: { ...

The mobile version of the page has extra white space at the bottom

I have a responsive design that is working well, but I am experiencing an issue on mobile devices where there is white space at the bottom of the page. * { margin: 0; padding: 0; box-sizing: border-box; } html { scroll-behavior: smooth; ...

Generate various routes and subroutes from an array

I need to create routes for an array of items, each with its own main page and nested pages. Here is an example structure: myapp.com/[item] (main item page) myapp.com/[item]/about (about item page) myapp.com/[item]/faq (faq item page) My goal is to itera ...

employing the d3.queue method to defer execution until receiving the AJAX response

Seeking examples of integrating AJAX, d3, and PHP to extract data from a database and create graphs. Any guidance would be appreciated. I am currently using d3 to generate a force chart based on database information retrieved through AJAX and PHP. I have ...

Customized webpage content using AJAX for interactive map selections

I have integrated JQVMaps into a WordPress website to display a dynamic world map. The goal is to update the content of the page based on the region that the user clicks. Below is a snippet of the code I have implemented as a proof of concept: <div ...

The type string[] cannot be assigned to type 'IntrinsicAttributes & string[]'

I'm attempting to pass the prop of todos just like in this codesandbox, but encountering an error: Type '{ todos: string[]; }' is not assignable to type 'IntrinsicAttributes & string[]'. Property 'todos' does not ex ...

Is it possible to vertically center a child div within its parent container using JavaScript when the page loads without explicitly setting its position?

Using JavaScript to vertically center a child div within a fluid container involves calculating the height of both elements and positioning the child div accordingly. However, one issue faced is that the position is not set when the page loads. To solve ...

utilize Angular's interface-calling capabilities

In the backend, I have an interface structured like this: export interface DailyGoal extends Base { date: Date; percentage: number; } Now, I am attempting to reference that in my component.ts file import { DailyGoal } from '../../interfaces' ...

Core MVC - Adjusting Font Size

After setting up an MVC Core App with automatic scaffolding, I am now faced with the challenge of adjusting the font size in my html View. The question is: How can I change the font size in bootstrap.css? There seem to be multiple font sizes available an ...

Problem with Ajax causing full-page reload

I currently have a webpage that utilizes JqueryUI-Mobile (specifically listview) in conjunction with PHP and some Ajax code. When the page loads initially, it displays a list generated from a MySQL DB. I want this list to refresh itself periodically witho ...

Transforming a JavaScript chained setter into TypeScript

I have been utilizing this idiom in JavaScript to facilitate the creation of chained setters. function bar() { let p = 0; function f() { } f.prop = function(d) { return !arguments.length ? p : (p = d, f); } return f; } ...

There seems to be an issue with updating the ng-model properly in angular-ui-tinymce

I have encountered a problem where I am attempting to add a DOM node when a custom button is clicked, but the model associated with the textarea is not being properly updated. To illustrate the issue, I have created a plunker as a demo. [https://plnkr.co ...

Navigate to the Bootstrap Panel body when the relevant link is clicked

I am facing an issue with a long list of panels that are tedious to scroll through. To make navigation easier, I am attempting to create a shortcut link at the top of the page. Below is the code for the shortcut: <a data-toggle="collapse" data-parent ...

How can I change the colors of points on a 3D scatter plot using Three.js as I zoom in?

Seeking assistance with a project involving displaying a 3D point cloud containing approximately 200K points, akin to the image provided below, complete with a colorbar. https://i.sstatic.net/L6ho0.png We are looking to dynamically update the colorbar wh ...

The jQuery mousedown() function seems to be malfunctioning and unable to trigger the drag event

I am attempting to initiate a drag event using jQuery. You can access the fiddle by clicking here http://jsfiddle.net/sgsvenkatesh/hepbob75/5/ I tried using the following code to initiate the drag event, but it doesn't seem to be working: $(documen ...

Create a file object using content with the help of JavaScript

I am working with a file containing specific data const ics = 'BEGIN:VCALENDAR\n' + 'VERSION:2.0\n' + 'CALSCALE:GREGORIAN\n' + 'METHOD:PUBLISH\n' + 'END:VCALENDAR\n'; I am trying t ...

Utilizing for loop and specific string selectors in an undefined AJAX post request

Greetings fellow developers! I have been exploring jquery/ajax and here is what I've put together: $(function() { $("#moreAdd").click(function() { var dataString = []; var selector = '#repeat0'; var row; for(var i=0;$ ...

Choose an option from a dropdown menu and assign it to a JavaScript variable

Is it possible to store the selected option from a dropdown list as a JavaScript variable, even when new Ajax content is loaded on the page? Below is a simple form code example: <form name="searchLocations" method="POST"> <select name="l ...

The issue arises in React when input elements fail to render correctly following a change in value, specifically when the keys remain identical

Click here to view the code sandbox showcasing the issue The code sandbox demonstrates two versions - a working one where Math.random() is used as the key, and a not working one where the index of the array is used as the key. When the array this.state.v ...