I need a pop up (facebook like share box) to be displayed when the the youtube video stops.
I already have lots of videos on my wordpress website. I need this to work for all my previous videos.
I've already tried this from another post here:
<html>
<head>
<title>YT Test</title>
<script type="text/javascript">
<!--
// 2. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');
tag.src = "http://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: 'ecccag3L-yw',
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
// The API will call this function when the video player is ready.
function onPlayerReady(event) { /* do nothing yet */ }
// The API calls this function when the player's state changes.
function onPlayerStateChange(event) {
if (event.data == YT.PlayerState.ENDED) {
// insert appropriate modal (or whatever) below
alert('I hope you enjoyed the video')
}
}
-->
</script>
</head>
<body>
<div id="player"></div>
</body>
<html>
isn't helping. This works only for one video. ecccag3L-yw in this case.
Can someone help me do this right?
here is an example of what I need. http://www.broascadilie.ro/index.php/video/item/29208-c%C3%A2nd-ea-are-chef-%C8%99i-tu-nu-when-she-is-in-the-mood-and-he-isnt
after the video ends, a pop up comes up for users to like and/or share.
This one isn't hard. You need to change videoId: 'ecccag3L-yw' to videoId: '<?php echo $id?>'
Also you need to make sure that in the $id variable is stored your video ID. Since you are using wordpress you should just make a connection to the database and get the value you are interested.
So about after the <title></title>
Related
I am looking to create sound buttons.
Have used the answer here:
Buttons click Sounds
and implemented it so that the buttons are divs and created dynamically from a MySQL DB.
Does anyone know how to preload that list of sounds on page load?
Also, I want to apply a CSS class to the div when clicked and then when the audio finishes, want it to switch back to the original CSS class.
This is what I have tried. The sounds play correctly but the onended fuction does not fire.
<script type='text/javascript'>
$(window).load(function(){
var baseUrl = "http://[URL HERE]";
var audio = [<?php echo $audiostring; ?>];
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = new Audio(baseUrl + audio[i-1]).play();
mySound.onended = function() {
alert("The audio has ended");};
});
});
</script>
If you are using HTML5 audio you can do something like the following:
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
Edit:
Try changing the way you create the audio tag, as referenced here.
$('div.ci').click(function() {
var i = $(this).attr('id').substring(1);
mySound = $(document.createElement('audio'));
mySound.src = baseUrl + audio[i-1];
mySound.play();
mySound.addEventListener("ended", function()
{
alert("The audio has ended");
});
});
<audio> and new Audio() should be the same but it doesn't look
like that is the case in practice. Whenever I need to create an audio
object in JavaScript I actually just create an element like
this:
The ended event is created based on .currentTime attribute. event-media-ended
the canplaythrough event was used to knowing when the browser has finished downloading the audio file and we can play
code complete use closest
<style type="text/css">
body{background: #aaa;color:#fff;}
div
{
width: 100px;
height: 100px;
background: #dda;
}
</style>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div >
</div>
<div >
</div>
<div >
</div>
<script type="text/javascript">
$(window).load(function(){
var audioFiles = [
"http://www.soundjay.com/button/beep-01a.mp3",
"http://www.soundjay.com/button/beep-02.mp3",
"http://www.soundjay.com/button/beep-03.mp3",
"http://www.soundjay.com/button/beep-05.mp3"
];
function Preload(url) {
var audio = new Audio();
// once this file loads, it will call loadedAudio()
// the file will be kept by the browser as cache
audio.addEventListener('canplaythrough', loadedAudio, false);
audio.src = url;
}
var loaded = 0;
function loadedAudio() {
// this will be called every time an audio file is loaded
// we keep track of the loaded files vs the requested files
loaded++;
if (loaded == audioFiles.length){
// all have loaded
init();
}
}
var player = document.createElement('audio');
function playAudio(index) {
player.src = audioFiles[index];
player.play();
}
function init() {
$('div').click(function(event) {
$(this).css('background', 'blue');
playAudio(Math.floor(Math.random()*audioFiles.length));
player.addEventListener("ended", function(){
player.currentTime = 0;
$(event.target).closest('div').css('background', '#dda');
});
});
}
// We begin to upload files array
for (var i in audioFiles) {
Preload(audioFiles[i]);
}
});
</script>
I am getting few errors while playing video using YouTube Player Tools - Iframe API.I am getting these 6 errors in the console window of my browser
1.Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ( 'https://www.youtube.com') does not match the recipient window's origin ('http://127.0.0.1').
2.GET chrome-extension://boadgeojelhgndaghljhdicfkmllpafd/cast_sender.js net::ERR_FAILED
3.GET chrome-extension://dliochdbjfkdbacpmhlcpmleaejidimm/cast_sender.js net::ERR_FAILED
4.GET chrome-extension://hfaagokkkhdbgiakmmlclaapfelnkoah/cast_sender.js net::ERR_FAILED
5.GET chrome-extension://fmfcbgogabcbclcofgocippekhfcmgfj/cast_sender.js net::ERR_FAILED
6.GET chrome-extension://enhhojjnijigcajfphajepfemndkmdlo/cast_sender.js net::ERR_FAILED
my index.php is
<html>
<head>
</head>
<body>
<div id='player'></div>
<!--iframe id="player" type="text/html" width="640" height="390"
src="https://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
frameborder="0"></iframe-->
<script>
var tag = document.createElement('script');
tag.src = "http://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
// 2. This code loads the IFrame Player API code asynchronously.
// 3. This function creates an <iframe> (and YouTube player)
// after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '500',
width: '500',
videoId: 'wbLBHYAd0kE',//videos[currentid],
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, 10000);
done = true;
}
}
function stopVideo() {
alert();
player.stopVideo();
}
</script>
</body>
</html>
What I need to do to remove these errors?
1st error:
turn
tag.src = "http://www.youtube.com/iframe_api";
into
tag.src = "https://www.youtube.com/iframe_api";
for errors 2-6: This is a known bug with the official Chromecast JavaScript library. Instead of failing silently, it dumps these error messages in all non-Chrome browsers as well as Chrome browsers where the Chromecast extension isn't present.
What Im trying to do: Display a loading gif or text... at the very least show a black screen before and during the time the php is being executed.
What I have tried.
I have tested using flush () and I get nothing until the entire php process is finished. I dont particularly like this concept either but I'll take anything.
I am considering using two pages to accomplish this though the current project is nearly complete and would take some time to consolidate the scattered html/php code.
Currently I'm doing 3-simpleXML_load_file(), 1-include(), 1-file_get_contents()
I have javascript function plotting data from one of the simpleXML_Load_file()...
Im up for moving parts of the code to a different file but it's a big task. So id like some advise or suggestions on how to proceed.
If I need to elaborate more just ask!
Thanks,
JT
<html>
<head>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
?>
<script type="text/javascript">
<!--Plot function-->
$(function()
{
var d =
[
<?php
//Pulling in hourly data to plot temp vs time
$i=0;
$array=array();
while ($i<=100)
{
echo '['. (strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000) .','.$weather_hourly->data->parameters->temperature->value[$i] .'],';
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$value = (string) $value;
$min_sec_array[] = $value;
}
?>
</script>
</head>
<body>
<div id=graph>
</div>
</body
The main way you can accomplish this is by using AJAX and multiple pages. To accomplish this, the first page should not do any of the processing, just put the loading image here. Next, make an AJAX request, and once the request is finished, you can show the results on the page or redirect to a different page.
Example:
File 1 (jQuery must be included also), put this in the body along with the loader animation:
<script language="javascript" type="text/javascript">
$(function(){
var mydata = {};
$.post('/myajaxfile.php', mydata, function(resp){
// process response here or redirect page
}, 'json');
});
</script>
Update: Here is a more complete example based on your code. This has not been tested and needs to have the jQuery library included, but this should give you a good idea:
File 1: file1.html
</head>
<body>
<?php
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
?>
<!-- Include jQuery here! Also have the loading animation here. -->
<script type="text/javascript">
$(function(){
$.get('/file2.php?Lat=<?php echo $lat; ?>&Lon=<?php echo $long; ?>', null, function(resp){
// resp will have the data from file2.php
console.log(resp);
console.log(resp['min_sec_array']);
console.log(resp['main']);
// here is where you will setup the graph
// with the data loaded
<!--Plot function-->
}, 'json');
});
</script>
<div id=graph>
</div>
</body
</html>
File 2: file2.php
I'm not sure if you needed the $min_sec_array, but I had this example return that as well as the main data you were using before.
$lat = $_POST['Lat'];
$long = $_POST['Lon'];
$weather_hourly = simplexml_load_file('http:....lat='.$lat.'&lon='.$long.'');
//Pulling in hourly data to plot temp vs time
$i=0;
$main = array();
$array=array();
while ($i<=100)
{
$main[] = array((strtotime($weather_hourly->data->{'time-layout'}->{'start-valid-time'}[$i])*1000), $weather_hourly->data->parameters->temperature->value[$i]);
$value = $weather_hourly->data->parameters->temperature->value[$i];
array_push($array,$value);
$i++;
}
foreach ($array as $key => $value)
{
$min_sec_array[] = (string) $value;
}
echo json_encode(array(
'min_sec_array' =>$min_sec_array,
'main' => $main
));
exit();
?>
I would recommend not to do this with plain html and php if u expect it modify the page after it is loaded. Because php is server side processing, so it is executed before the page is send to the user. U need Javascript. Using Javascript will enable u to dynamically add or remove html elements to or from the DOM tree after the page was send to the user. It is executed by the users browser.
For easier start I would recommend jQuery, because there are lots of tutorials on such topics.
JQuery
JQuery learning center
A small example:
HTML
<head>
<meta charset="utf-8" />
<title> </title>
<script type="text/javascript" src="js/lib/jquery-1.9.1.js"></script>
</head>
<body>
<h1>Addition</h1>
<div id="error_msg"> </div>
<div id="content">
<!-- show loading image when opening the page -->
<img src="images/loading.gif"/>
</div>
<script type="text/javascript">
// your script to load content from php goes here
</script>
</body>
this will be nothing more then the following until now:
adding the following php file
<?php
$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
$result = $num1 + $num2;
echo '<p>Calculating '.$num1.' + '.$num2.' took a lot of time, but finally we were able to evaluate it to '.$result.'.</p>'
.'<p> '.$num1.' + '.$num2.' = '.$result.'</p>';
?>
wont change anything of the html, but adding javascript/ Jquery inside the HTML will be kind of connection between static html and server side php.
$(document).ready(function(){
$.ajax({ // call php script
url: 'php/script.php?num1=258&num2=121',
type:'GET',
timeout: 500,
contentType: 'html'
}).success(function(data){
// remove loading image and add content received from php
$('div#content').html(data);
}).error(function(jqXHR, textStatus, errorThrown){
// in case something went wrong, show error
$('div#error_msg').append('Sorry, something went wrong: ' + textStatus + ' (' + errorThrown + ')');
});
});
This will change your page to show the loading animation until the php script returns its data, like:
So you can setup the whole page in plain html, add some loading gifs, call several php scripts and change the content without reloading the page itself.
It is kind of nasty solution to your problem...
But this can work:
You work with those -
ob_start();
//printing done here...
ob_end_flush();
at the beginning you will create your rotating ajax gif...
Then you do all the processing and calculating you want...
At the end of the processing, just echo a small script that does a hide to your gif...
Depends on the exact need, maybe ajax can be more elegant solution.
In response to your conversation with David Constantine below, did you try using ob_flush()?
ob_start();
echo '<img src="pics/loading.gif">';
ob_flush();
// Do your processing here
ob_end_flush();
I think you don't have a problem with flushing your PHP output to the browser, but more likely with getting the browser to start rendering the partial html output. Unfortunately, browser behavior on partial html is browser-specific, so if you want something to work the same in any browser, the AJAX solution suggested in other answers is the better way to go.
But if you don't like that added complexity of a full AJAX solution, you can try to make your html output "nice" in the sense of providing some body output that can be formatted without needing the rest of the html output. This is were your sample code fails: It spends most of its time outputting data into a script tag inside the html header. The browser never even sees the start of the body until your PHP code has practically finished executing. If you first write your complete body, then add the script tag for the data there, you give the browser something to at least try to render whilst waiting for the final script to be completed.
I've found the same issue (albeit not in PHP) discussed here: Stack Overflow question "When do browsers start to render partially transmitted HTML?" In particular, the accepted answer there provides a fairly minimal non-AJAX example to display and hide a placeholder whilst the html file hasn't completely loaded yet.
I know this is an old question, but the answer provided in this page by rpnew is extremely clear and easy to adjust to your project's requirements.
It is a combination of AJAX and PHP.
The HTML page PHPAjax.html which calls the PHP script:
<html>
<head>
<script type="text/javascript">
document.write('<div id="loading">Loading...</div>');
//Ajax Function
function getHTTPObject()
{
var xmlhttp;
if (window.ActiveXObject)
{
try
{
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E)
{
xmlhttp = false;
}
}
}
else
{
xmlhttp = false;
}
if (window.XMLHttpRequest)
{
try
{
xmlhttp = new XMLHttpRequest();
}
catch (e)
{
xmlhttp = false;
}
}
return xmlhttp;
}
//HTTP Objects..
var http = getHTTPObject();
//Function which we are calling...
function AjaxFunction()
{
url='PHPScript.php';
http.open("GET",url, true);
http.onreadystatechange = function()
{
if (http.readyState == 4)
{
//Change the text when result comes.....
document.getElementById("content").innerHTML="http. responseText";
}
}
http.send(null);
}
</script>
</head>
<body onload="AjaxFunction()">
</body>
</html>
The Background PHP Script PHPScript.php:
<?php
sleep(10);
echo "I'm from PHP Script";
?>
Save both files in the same directory. From your browser open the HTML file. It will show 'Loading...' for 10 seconds and then you will see the message changing to "I'm from PHP Script".
OK so im trying to have a webpage that rotates every 30 seconds now i have what i need for this but instead of using an array like in what i have now see code below
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Rotating Page</title>
<style type="text/css">
* {
margin:0;
padding:0;
border:0;
}
html, body, iframe {
height:100%;
width:100%;
overflow:hidden;
}
</style>
<script type="text/javascript">
var pages = new Array(); // this will hold your pages
pages[0] = 'MY-LINK-HERE';
pages[1] = 'MY-LINK-HERE';
pages[2] = 'MY-LINK-HERE';
pages[3] = 'MY-LINK-HERE';
pages[4] = 'MY-LINK-HERE';
pages[5] = 'MY-LINK-HERE';
var time = 30; // set this to the time you want it to rotate in seconds
// do not edit
var i = 1;
function setPage()
{
if(i == pages.length)
{
i = 0;
}
document.getElementById('holder').setAttribute('src',pages[i]);
i++;
}
setInterval("setPage()",time * 1000);
// do not edit
</script>
</head>
<body>
<iframe id="holder" src="MY-SPLASH-PAGE-HERE" frameborder="0" scrolling="no"></iframe>
</body>
</html>
where in MY-LINK-HERE for the pages array i would like to use my rss link and get the list of links and add them to the pages array or something similar
my rss link is http://directitpros.com/cbm/wp/?feedpages
so i just want to load the text in the pages variable
It took me some time but I got it (tested and working)
This example uses jQuery and jGFeed.
jGFeed is a plugin for jQuery to do anything you want with RSS feeds.
In the HTML source you can get the URL of the plugin to save it.
Observations:
1. Your RSS link is not working properly, please check it!
(http://directitpros.com/cbm/wp/?feedpages)
When using your link I receive this error from the plugin I am using in browser console:
"Uncaught TypeError: Cannot read property 'feed' of null"
2. Make sure the links you want to use in iframe are able to browse by iframe:
Example:
If URLs are not able to browse by iframe you will get this message in your browser console and your iframe will be empty:
"Refused to display document because display forbidden by X-Frame-Options."
3. If you find a working RSS url and links from it fit the above requirements, use this live example I made to test:
http://jsfiddle.net/oscarj24/qWdqc/
(Check browser console and check messages that will appear)
Let's go with the code :-)
HTML:
<script src="http://code.jquery.com/jquery-latest.js" type="text/javascript"></script>
<script src="http://dl.dropbox.com/u/15208254/stackoverflow/jquery.jgfeed.js" type="text/javascript"></script>
<iframe id="holder" src="" frameborder="0" scrolling="no"></iframe>
CSS:
html, body, iframe {
height:100%;
width:100%;
overflow:hidden;
}
JS:
// Array containing pages
var pages = new Array();
// Time in seconds to rotate pages
var time = 30;
// Variable for loop purpose
var i = 1;
$(function(){
$.jGFeed('http://working-rss-url',
function(feeds){
// Check for feeds
if(!feeds){
// There was an error, remote url not ok or no feeds
return false;
}
// Do whatever you want with feeds here
for(var i=0; i<feeds.entries.length; i++){
var entry = feeds.entries[i];
// Fill array with RSS entries
pages.push(entry);
}
// If array contains urls
if(pages.length != 0){
// Rotate pages every 'x' seconds
setInterval(function() {
if(i == pages.length){
i = 0;
}
// Replace iframe scr with RSS entry link every 'x' seconds
$('#holder').attr('src', pages[i].link);
i++;
}, time * 1000);
}
}, 5); // Number of feeds you want to recover
});
Hope this helps.
Is there a way to track play counts for embedded videos? Ideally without resorting to a thumbnail linked to launch the embed / iframe code.
Example (try it yourself on jsFiddle):
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Example</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>
</head>
<body>
<div id="log"></div>
<ul>
<li class="video" id="video1"><iframe width="480" height="390" src="http://www.youtube.com/embed/z6lL83wl31E" frameborder="0" allowfullscreen></iframe><li>
<li class="video" id="video2"><iframe src="http://player.vimeo.com/video/28231570?title=0&byline=0&portrait=0" width="400" height="225" frameborder="0"></iframe></li>
<li class="video" id="video3"><embed flashVars="playerVars=autoPlay=no" src="http://www.metacafe.com/fplayer/3153323/the_three_stooges_minisode_beer_barrel_polecats_season_1_episode_0008.swf" width="440" height="248" wmode="transparent" allowFullScreen="true" allowScriptAccess="always" name="Metacafe_3153323" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash"></embed></li>
</ul>
<script>
/* Here's what I've tried so far: */
$('.video').mouseover(function(){
$('#log').html('Mouseover!');
/*alert('Track mouseovers instead? Is this the best I can do?');*/
});
$('.video').mouseout(function(){
$('#log').html(' ');
});
$('.video').mousedown(function(){
$('#log').html('Mousedown!');
alert('mousedown');
/* This will track mousedown events in embed objects (not iframes), but not allow the click event to pass through to object. */
});
</script>
</body>
</html>
How can I track play counts for each of these videos?
Ryan, the only way to do this is to use the video sharing site's player api(s), as html and javascript have no native support for this.
To do this for youtube videos, you can check out the documentation here
To do this for vimeo videos, you can check out the documentation here
This works for Vimeo... Triggers a javascript alert on the "Play" event but there are a number of other events like "finished", "pause", "playProgress" (constantly updating while video is playing)... Uses Jquery
$(document).ready( function () {
var f = $('iframe'),
url = f.attr('src').split('?')[0],
status = $('.status');
// Listen for messages from the player
if (window.addEventListener){
window.addEventListener('message', onMessageReceived, false);
}
else {
window.attachEvent('onmessage', onMessageReceived, false);
}
// Handle messages received from the player
function onMessageReceived(e) {
var data = JSON.parse(e.data);
switch (data.event) {
case 'ready':
onReady();
break;
case 'play':
onPlay();
break;
}
}
// Call the API when a button is pressed
$('button').on('click', function() {
post($(this).text().toLowerCase());
});
// Helper function for sending a message to the player
function post(action, value) {
var data = { method: action };
if (value) {
data.value = value;
}
f[0].contentWindow.postMessage(JSON.stringify(data), url);
}
function onReady() {
status.text('ready');
post('addEventListener', 'play');
}
function onPlay() {
alert("Dude done clicked 'Play'");
}
});