JavaScript effect to make a div with a YouTube video fade in and out

I have limited knowledge of javascript, but I am curious if this idea can be achieved:

I want to make the videos on my webpage invisible initially. When a user clicks on one of my links, I want a YouTube embed to fade in and start playing. Then, when the user hovers over or moves their mouse away, I want the video to fade out and then be able to fade in again on hover. However, I am struggling to get it to work properly. I have tried different solutions from stackoverflow like this jsFiddle: http://jsfiddle.net/VKzxy/

Below is the jQuery code I've been working on:

/* elt: Optionally, a HTMLIFrameElement. This frame's video will be played,
     *       if possible. Other videos will be paused*/
    function playVideoAndPauseOthers(frame) {
        $('iframe[src*="http://www.youtube.com/embed/"]').each(function(i) {
            var func = this === frame ? 'playVideo' : 'pauseVideo';
            this.contentWindow.postMessage('{"event":"command","func":"' + func + '","args":""}', '*');
        });
    }
    $('#links a[href^="#vid"]').click(function() {
        var frameId = /#vid(\d+)/.exec($(this).attr('href'));
        if (frameId !== null) {
            frameId = frameId[1]; // Get frameId
            playVideoAndPauseOthers($('#playlist' + frameId + ' iframe')[0]);
            $($('#playlist' + frameId + ' iframe')[0]).fadeIn(750);
            
            //When hovering, fadeIn.
            $('#content').mouseenter(function(){
                $($('#playlist' + frameId)[0]).fadeIn(750);
            });
            
            //When leaving, fadeOut.  
            $($('#playlist' + frameId)[0]).mouseleave(function(){
                $($('#playlist' + frameId)[0]).fadeOut(750);
            });
        }
    });

Note: The solution does not necessarily have to be in javascript. Any method that achieves the desired functionality would be acceptable.

Answer №1

Make sure to follow these steps:

  • Stop all video playback

  • Hide all videos from view

  • Display the desired video on screen

  • Start playing the selected video

Check out the solution here:

http://jsfiddle.net/5Yxhj/6/

IMPORTANT

In order for the fade effect to function properly, ensure that the wmode is set to opaque as demonstrated in the jsfiddle example.

src="http://www.youtube.com/embed/a-TrP8Z3Cb8?wmode=opaque& (...)

This setting enables jQuery's opacity effects (like fadeIn or fadeOut) to work seamlessly over the flash object, such as when changing the opacity of an iframe.

BELOW IS THE JAVASCRIPT CODE USED IN THE FIDDLE

function hideAll()
{
    $('#content').children('div').each(function()
    {
        $(this).hide();
    });
}

function fadeAll(strClickId)
{
    var elems = $('#content').children('div'), count = elems.length;

    elems.each(function()
    {
        $(this).fadeOut(750, function()
        {
            $(this).children('iframe')[0].contentWindow.postMessage(
                JSON.stringify({
                    "event": "command",
                    "func": "pauseVideo",
                    "args": ""
                }), "*"
            );
            if (!--count)
            {
                $(strClickId).fadeIn(750, function()
                {
                    $(strClickId).children('iframe')[0].contentWindow.postMessage(
                        JSON.stringify({
                            "event": "command",
                            "func": "playVideo",
                            "args": ""
                        }), "*"
                    );
                });
            }
        });
    });
}

$(window).load(function()
{
    hideAll();
});

$('#links a[href^="#vid"]').click(function()
{    
    var frameId = '#playlist' + $(this).attr('href').substr(4);
    fadeAll(frameId);
});

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

"Resolving the issue of Django request.FILE returning a null value

HTML Template: <form method="post" action="" enctype="multipart/form-data" class="form-group"> {% csrf_token %} <h1 class="m-3 text-center">New Post</h1> <div id="tui-image-e ...

Customizing media queries, Overriding styles from parent elements

Currently tackling a responsive website design challenge where I'm dealing with conflicting styles in media queries and parent css. Here's the CSS from the parent style sheet: .sec1 p { text-align: left; width: 55%; margin-left: 8%; float:lef ...

Unveiling the secrets of leveraging Vue Router global navigation guard to efficiently verify multiple conditions

Within a Vue 3 application utilizing Pinia, my objective is to accomplish the following: Direct a user to the sign-in page when authentication is not verified. Direct a user to a verification page if authenticated but not yet verified. Direct a user to th ...

Exploring Jasmine and AngularJS: Testing a factory function in the context of dependency injection

Looking to create a unit test for a simple factory that calculates the sum of two numbers. (function () { "use strict"; angular .module("math") .factory("addservice", [addTwoNumbers]); function addTwoNumbers(a, b) { ...

What is the process for conducting a comprehensive match search using dual parameters?

I am working with a database model Schema({ members: [ { type: String, required: true, ref: "User" } ], createdAt: { type: Date, default: Date.now(), required: true }, lastMessage: { message: { typ ...

The withRouter function in React Router does not automatically inject the router

Desiring to implement withRouter on my primary React component named 'App'. You can view the documentation here. This is how I utilize it: import React from "react"; import { render } from "react-dom"; import {Router, Link, hashHistory, Rout ...

The d3 hierarchy possesses the capability to compute the average values of child nodes

Looking for a solution with d3 visualization that involves averaging up the value of score on the lowest nodes and dynamically adding that average to the parent node above. It seems like there isn't an easy method in d3 for this task. The desired outc ...

What is the best way to include dynamic query parameters in the src attribute of a <script> tag?

As I develop a basic asp.net application, I encountered a situation where I needed to include a script with a dynamic query parameter in my aspx page. For instance: <script src="../javascript/script.js?v=#var#" type="text/javascript"></script> ...

Tips for aligning the navigation bar in the center

I recently came across a simple tutorial on w3schools (article) for creating a responsive menu. However, I've been struggling to center it horizontally for the past few days. Here is the HTML code: <ul class="topnav"> <li><a href=" ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Error message: Unknown scope- unable to process 'files-path' Android File provider issue

My current project involves implementing file system access in react native Android. However, when attempting to add 'files-path' in XML, an error stating "Error: Unsupported type 'files-path'" is encountered. I am utilizing the react n ...

Tips for transferring information from ng-view to the navbar on the index.html page using AngularJS

Recently, I embarked on a journey to learn the MEAN stack and decided to challenge myself by building an authentication page from scratch instead of using the out-of-the-box solution. My main struggle lies in updating texts on my navbar. Here's a snip ...

Angucomplete Alternative solves the challenge of accessing remote URLs

I have been using the Angucomplete Alt directive for creating an autocomplete feature. It has been working well so far, but now I want to customize a specific request to be sent to my server. <div angucomplete-alt id="input-name" ...

Searching for Random Images in Discord using JavaScript is a fun and interactive way

I'm currently working on developing a Discord bot using discord.js to generate random images. Initially, I successfully implemented this functionality for cursed images. However, when I attempted to adapt the code for 'mcimage' to display Mi ...

Having trouble reaching the upload file in PHP

I am attempting to transfer files to a remote server using JavaScript, with PHP as the backend. The JavaScript code seems to be functioning properly, but on the PHP side, the $_FILES and $_POST arrays are empty. However, the $_SERVER array contains some da ...

Is there a way to incorporate an MTN Momo or Orange Money payment system into your application if you are not a registered business entity?

Implementing an MTN Momo and Orange Money payment system through their respective APIs is crucial. In addition, I am seeking a dependable and effective method to seamlessly integrate these diverse APIs. During my attempt to incorporate the API via their ...

How can I modify the CSS of every fourth element using jQuery?

Is there a way for jQuery to update the styling of every fourth item (div) within another div? I've been searching without success... Any guidance would be greatly appreciated :) ...

Steps for showing personalized validation error messages in Angular 7

Is there a way to highlight the input field of a form with a red border and display the message Password is invalid when a user types in a password that does not match the set password? I have managed to see the red border indicating an error when I enter ...

Experiencing a hiccup in React while attempting to play an mp3 file

My project includes the following code snippet, with an example mp3 file and npm package: https://www.npmjs.com/package/react-sound import React from 'react'; import Sound from 'react-sound'; class CustomSound extends React.Component ...

In order to leave a comment, I need to click on the button two times

Whenever I click on a button within a form, the comment should appear alongside the email and a small avatar. However, I'm facing an issue where I have to click the button twice for it to work as expected. This problem is rooted in some complications ...