I'm in a sticky situation.
I'm trying to add a YouTube Video to my website that autoplays...I've done that...However, is there a way to tell if this person has visited this site already, like using cookies, or something even easier (I don't know how to use cookies haha) and then NOT autoplay if they've visited the site more than once?
I could imagine it could get quite annoying if you visit a website 3 or 4 times, and this video keeps playing every time you visit!
Here's the code I've got so far...
<iframe width="455" height="256" src="https://www.youtube.com/embed/qYTlJdYe0lw?rel=0&autoplay=1;showinfo=0" frameborder="0" allowfullscreen></iframe>
Thanks heaps for your help in advance!
here some live example by jsfiddle:
Play youtube video only once at first page visit.
I am using cookies and youtube JavaScript API.
<!-- html -->
<div id="video_container"></div>
//JavaScript
$(document).ready(function() {
//inject script tag in dom with iframe-api as source
//on success this will call function "onYouTubeIframeAPIReady"
//more info https://en.wikipedia.org/wiki/JSONP
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
//this is only for testing reason
//remove cookie
$('button').on('click', function(){
document.cookie = "yt_video=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
});
});
var player;
function onYouTubeIframeAPIReady() {
//JavaScript API is loaded -> create player
//more info https://developers.google.com/youtube/iframe_api_reference#Getting_Started
player = new YT.Player('video_container', {
height: '390',
width: '640',
videoId: 'SzPfOuFvlfs',
events: {
'onReady': onPlayerReady
}
});
};
function onPlayerReady() {
//check if cookie exist. If not set one and play video
if (getCookie('yt_video') === '') {
document.cookie="yt_video=SzPfOuFvlfs";
player.playVideo();
}
}
// helper function
// get cookie value
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
return "";
}
Related
How do I insert a youtube web page into my HTML web page using I frame,
and please I need a code snippet that I can run to see how it looks like.
There are multiple ways to start a video on the web page.
Below can work out.
<iframe width="420" height="345" src="https://www.youtube.com/embed/tgbNymZ7vqY?autoplay=1">
</iframe>
<div id="player"></div>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
player.setPlaybackRate(2);
event.target.playVideo();
}
I want to display youtube videos in iphone cordova app,
I tried iframe but it is not displaying some times.
So trying object tag
my code is
<div style="width: 100%; padding: 0" id="getWidth">
<object width="100%" height="auto">
<param name="movie" value="http://www.youtube.com/v/{{youtubeId}}">
<embed src="http://www.youtube.com/v/{{youtubeId}}" type="application/x-shockwave-flash" width="100%;" height="auto">
</object>
</div>
here getWidth is taking full screen but video is not showing in full width as shown in the following image
Note: left side safari inspector and right side iphone simulator
Image is taken while trying to set width dynamically but in both cases result is same
Refer to the Youtube Player API for how to embed it in your application. Iframe is by far the best way to go.
Here is a sample html from the API
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</body>
</html>
I am using the YouTube API as the following:
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
playerVars: { 'modestbranding': 1, 'showinfo' : 0, 'controls': 0 },
videoId: 'M7lc1UVf-VE'
});
}
</script>
I have a div that is named player on my html.
I need the video to not have the controls (controls=0). The problem is whenever I remove the controls instead of them there is a black bar. Instead of that black bar replacing the controls, I want the video to expand and take the whole video's height&width.
Am I missing anything here? Thanks for any light on that matter.
Try to add this in your 'playerVars' :
'autoplay' : 0
It seems that the video dimensions doesn't match the values of your variables.
This looks better (e.g. height: '360'):
<html>
<head>
<title>YT - Test</title>
<script>
// Load the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/player_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '360',
width: '640',
playerVars: { 'modestbranding': 1, 'showinfo' : 0, 'controls': 0 },
videoId: 'M7lc1UVf-VE'
});
}
</script>
</head>
<body>
<div id="ytplayer"></div>
</body>
</html>
Please see https://developers.google.com/youtube/youtube_player_demo
While working on this locally, chrome, safari and firefox (all on OS X) all scrolled to the proper locations when using the menu at the bottom.
Now that it's being accessed online (from a windows machine), chrome doesn't scroll to the right locations, but IE does. Interestingly, mobile safari is also having the same issue.
Each link in the footer at the bottom should scroll to its corresponding 'label'. IE does that fine, but chrome just puts me 'sort of near' there.
http://www.colinandmya.com/sitetest/index.html
Any help is greatly appreciated.
** EDIT: ADDED A JSFIDDLE **
(i hope i did it right... thanks again for letting me know the process)
http://jsfiddle.net/prefekt/aKJ3Y/
$(document).ready(function() {
function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]
{3,4}$/,'')
.replace(/\/$/,'');
}
$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) ==
filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId
= $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId :
$targetAnchor.length ? $targetAnchor : false;
if ($target) {
var targetOffset = $target.offset().top;
$(this).click(function() {
$('html, body').animate({scrollTop: targetOffset}, 1000);
return false;
});
}
}
});
});
I think that the problem is how you are embedding the youtube video. z-index is ignored
try this script to fix
$(document).ready(function(){
$('iframe').each(function(){
var url = $(this).attr("src");
var char = "?";
if(url.indexOf("?") != -1){
var char = "&";
}
$(this).attr("src",url+char+"wmode=transparent");
});
});
or just embed video in this way
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/xxxxxx?wmode=transparent" frameborder="0" wmode="Opaque">
and not in this way
<iframe title="YouTube video player" width="480" height="390" src="http://www.youtube.com/embed/xxxxx" frameborder="0" wmode="Opaque">
Move the following line:
var targetOffset = $target.offset().top;
To within the click event:
$(this).click(function() {
var targetOffset = $target.offset().top;
$('html, body').animate({scrollTop: targetOffset}, 1000);
return false;
});
The variable was being set outside of the click event and this the targetOffset was not a current value when clicked. For more information on this, look up Javascript variable scope.
To my problem, I have one link . I want to play the video by clicking the link in a fancybox overlay window. This is not a problem. The problem is the parameters, for example "autoplay" or "autohide".
The following link doesn't work:
The Overlay-Window opened, but the video is not playing automatically.
EDIT: I want to use the HTML5 Player on mobile devices. On a desktop-browser it works with the parameters, but not on mobile devices.
As it turns out, autoplay cannot be done on iOS devices (iPhone, iPad, iPod touch) and Android.
See https://stackoverflow.com/a/8142187/2054512 and https://stackoverflow.com/a/3056220/2054512
Have a look on code below.
Tested and found working on Mobile and Tablet devices.
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.playVideo();
}
// 5. The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 6000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
The code below was tested on iPhone, iPad (iOS13), Safari (Catalina). It was able to autoplay the YouTube video on all devices. Make sure the video is muted and the playsinline parameter is on. Those are the magic parameters that make it work.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, minimum-scale=1.0, user-scalable=yes">
</head>
<body>
<!-- 1. The <iframe> (video player) will replace this <div> tag. -->
<div id="player"></div>
<script>
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
width: '100%',
videoId: 'osz5tVY97dQ',
playerVars: { 'autoplay': 1, 'playsinline': 1 },
events: {
'onReady': onPlayerReady
}
});
}
// 4. The API will call this function when the video player is ready.
function onPlayerReady(event) {
event.target.mute();
event.target.playVideo();
}
</script>
</body>
</html>
The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.
Reference: https://developers.google.com/youtube/iframe_api_reference
There is a way to make youtube autoplay, and complete playlists play through. Get Adblock browser for Android, and then go to the youtube website, and and configure it for the desktop version of the page, close Adblock browser out, and then reopen, and you will have the desktop version, where autoplay will work.
Using the desktop version will also mean that AdBlock will work. The mobile version invokes the standalone YouTube player, which is why you want the desktop version of the page, so that autoplay will work, and so ad blocking will work.
How to use a Youtube channel live url to embed and autoplay. Instead of Video ID that has to be constantly updated for live stream changes.
I mixed two sets of code and came up with a working auto play Youtube video embed from a channel live stream.
My thanks to both of the other contributors for their help. Hopefully this helps someone else some time.
Example stream
https://www.youtube.com/embed/live_stream?channel=UCwobzUc3z-0PrFpoRxNszXQ
The code below by Zubi answered Nov 25 '16 at 7:20 works with Youtube videos.
With code by Darien Chaffart found at
https://stackoverflow.com/a/61126012/1804252
Example
<html>
<head>
</head>
<body>
<center>
<script src="https://www.youtube.com/iframe_api"></script>
<!-- Insert Livestream Video -->
<iframe id="live-video" src="https://www.youtube.com/embed/live_stream?channel=UCwobzUc3z-0PrFpoRxNszXQ&enablejsapi=1" width="100%" height="100%" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen enablejsapi="1"></iframe>
<!-- Basic API code for Youtube videos -->
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('live-video', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
function onPlayerReady() {
var url = player.getVideoUrl(); /*Use Youtube API to pull Video URL*/
var match = url.match(/[?&]v=([^&]+)/);
var videoId = match[1]; /*Use regex to determine exact Video URL*/
// Insert a new iFrame for the livestream chat after a specific div named chatframe*/
var livevid = document.createElement("iframe");
livevid.src = 'https://www.youtube.com/live_chat?v=' + videoId + ''
livevid.width = '100%';
livevid.height= '100%';
document.getElementById("chatframe").appendChild(livevid);
}
function onPlayerStateChange() {
}
function onPlayerReady(event) {
event.target.playVideo();
}
// The API calls this function when the player's state changes.
// The function indicates that when playing a video (state=1),
// the player should play for six seconds and then stop.
var done = false;
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.PLAYING && !done) {
setTimeout(stopVideo, 90000000);
done = true;
}
}
function stopVideo() {
player.stopVideo();
}
</script>
</center>
</body>
</html>