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

Is there a way to conceal the horizontal divider in the login form of the ionic HTML mobile user interface?

While designing this login form on the HTML ionic mobile UI, everything looks good except for one thing - I want to hide the horizontal line that appears between the "Forgot Password" label and the LOGIN button. Is there a way to do this? Login.html: < ...

The interaction issue in Ionic 4 with Vue js arises when the ion-content within the ion-menu does not respond to clicks

My Vue app has been set up with Ionic 4 using @ionic/vue. Below is the code snippet from the main.js file: import Vue from 'vue' import App from './App.vue' import router from './router' import store from './store&apos ...

Failure to Fetch the Uploaded File's Value Using the Parameter

Objective: My aim is to automatically upload the second input named "file2" to the action result using jQuery code that is compatible with the latest versions of Firefox, Chrome, and Internet Explorer. Issue: The problem arises when HttpPostedFileBase ...

Having trouble publishing project on Vercel because of a naming issue

Whenever I try to deploy a project on vercel, I encounter an error stating that the project name is not valid. The specific error messages are as follows: Error: The name of a Project can only contain up to 100 alphanumeric lowercase characters and hyphe ...

A peaceful WCF service initiates a client callback whenever a server update occurs

In the process of developing a WCF RESTFUL service on top of a c++ console application, I am confronted with an issue. The client accesses this c++ application through my restful wcf service using a browser. Every time there is an update received by my w ...

There seems to be a hiccup in the JavaScript Console. It could potentially impact the functionality

Hey there, I'm encountering a strange issue in my IE 11 console. A JavaScript Console error has occurred. This may impact functionality. Whenever I try to run a for loop to create a list of elements within a ul tag 4000 times, the process stops at ...

Vue Material - Effortlessly integrate native transitions within router views

In the project I'm currently working on, I have chosen to use Vue Material for the development of a single-page application. The approach I am taking follows a common trend in which a central "container" component is utilized to manage the shifting vi ...

Encountering spacing problems on IE9 and FF11 while using OS X

After conducting some testing on a design I coded, I found that it functions well in FF 13, Chrome 21, IE 7/8, and Opera 11.62 for Windows, as well as Safari 5.1 for OS X. Unfortunately, since I only have WinXP, I had to utilize Adobe Browserlab to test f ...

ES6 syntax specification allows for the use of a fat arrow function for declaring React components

When learning React, I have noticed two different ways of declaring components. The first is using the classic fat arrow syntax with a return statement. const Component = () => { return ( <div>Hello</div> ) } Recently, I came ...

Discover the ins and outs of utilizing the Google+ Hangout API specifically for chatting purposes

I am currently working on a webpage and I want to include a hangout button that will allow users to connect with me and start chatting automatically when clicked. Here is the code I have so far: <script src="https://apis.google.com/js/platform.js" asy ...

The use of Material-UI collapse animation in a table results in the insertion of div elements, triggering a validateDOMNesting warning

Having a data-filled table, I am looking to implement smooth transitions when adding or deleting an item. This is a ReactJS project utilizing Material-UI. The desired effect is similar to the one demonstrated in their example. While they use a List compon ...

Having trouble properly implementing variable updates when creating a multi-theme website

I have a Next.js app and a globals file containing all the themes: body { margin: 0; font-family: Inconsolata, monospace; background-color: var(--bg-color); } :root { --bg-color: #262a33; --main-color: #43ffaf; --sub-color: #526777; --sub-al ...

Angular Material Toolbar Experiencing Color Distortion

To see the issue in action, check out this CodePen: An ongoing problem I've encountered with Angular Material involves distorted colors on the toolbar. The edges of the toolbar display one shade of green, while the middle shows a different shade. Tak ...

An issue occurred: TypeError - Unable to access the 'subscribe' property of an undefined object during a POST HTTP request in Angular [8]

I'm currently attempting to send data to a REST API using Postman. I am encountering an issue where I receive the error "Cannot read property 'subscribe' of undefined" when making a POST HTTP call, as shown in the console log: https://i.sta ...

Saving JavaScript Object Notation (JSON) information from Node.js into MongoDB

Currently, I am successfully pulling weather data in JSON format from Wundground using their API. The next step for me is to store this data in MongoDB for future use. After retrieving the data and attempting to write it to a Mongo collection, I encountere ...

What is the formula to determine if x is greater than y and also less than z?

I need help determining if a number falls within the range of greater than 0 but less than 8 using JavaScript. Can anyone assist me with this? Here is my attempt at it: if (score > 0 && score < 8) { alert(score); } ...

What is the best way to adjust the placement of a component to remain in sync with the v-model it is connected to?

I am encountering an issue with 2 sliders in my project. I have set it up so that when the lower slider's value is greater than 0, the top slider should automatically be set to 5. I am using a watcher function for this purpose. However, if I manually ...

Adjust iFrame to allow scrolling dynamically

I am currently facing a challenge with creating a non-scrollable iframe element using JavaScript. The function I need to call is within an iframe, and while it works on Firefox and Chrome, I also need it to work on Internet Explorer. My solution involves ...

I'm having trouble understanding why I am not receiving any response with the "form.submit()" function inside xhr.onreadystatechange() in JavaScript/AJAX

When I try to use the form.submit() function in response to xhr.onreadystatechange, it doesn't work as expected. Below is my login form: <form action="user_home.php" method="post" id="loginForm" > <tr> <td colspan=2>Members ...

The functionality of enabling and disabling dynamic behavior in AngularJs is not functioning as anticipated

As a newcomer to AngularJS, I may have some basic questions. I am currently working on implementing dynamic behavior for a button click event, but it's not functioning as expected. Could this be due to an issue with scope? Below is my HTML code: < ...