How To Create A Timed Button For A Video Using Wistia API - javascript

Hi I am trying to get a button to appear beneath my video after 30 mins and 30 seconds. When I contacted Wistia support they gave me this link and told me they were not coders and couldn't help me further. I don't know anything about javascript and I do know a bit of CSS. I read a post on another website here and copied it to my site hoping that it would work. I added the javascript code beneath the inline embed of my video, and then put the CSS in the customize additional css editor in wordpress.
When I did it part of it worked and the button I had there disappeared, but when I tried to trigger it at the 30min 30sec mark it never appeared and I haven't been able to get it to appear at all. Here is a link to the page for you to view it and below is the code that I have used to embed the video as well as the css to hide the button. Any help would be greatly apprecited as I am very new to this.
Here is the code I used on the video embed:
<script src="https://fast.wistia.com/embed/medias/c5khj4dcbi.jsonp" async></script><script src="https://fast.wistia.com/assets/external/E-v1.js" async></script><div class="wistia_responsive_padding" style="padding:56.25% 0 0 0;position:relative;"><div class="wistia_responsive_wrapper" style="height:100%;left:0;position:absolute;top:0;width:100%;"><div class="wistia_embed wistia_async_c5khj4dcbi videoFoam=true" style="height:100%;position:relative;width:100%"><div class="wistia_swatch" style="height:100%;left:0;opacity:0;overflow:hidden;position:absolute;top:0;transition:opacity 200ms;width:100%;"><img src="https://fast.wistia.com/embed/medias/c5khj4dcbi/swatch" style="filter:blur(5px);height:100%;object-fit:contain;width:100%;" alt="" aria-hidden="true" onload="this.parentNode.style.opacity=1;" /></div></div></div></div>
<script>
window._wq = window._wq || [];
// target our video by the first 3 characters of the hashed ID
_wq.push({ id: "c5khj4dcbi", onReady: function(video) {
// at 1830 seconds (30.5min x 60 = 1830), do something amazing
video.bind('secondchange', function(s) {
if (s === 1830) {
// Insert code to do something amazing here
// console.log("We just reached " + s + " seconds!");
$( "#mybutton" ).addClass( "ShowMeButton" );
}
});
}});
</script>
And here is the CSS I used on the wordpress editor customize > additional CSS:
.page-id-741 #mybutton {
opacity: 0;
}
.ShowMeButton {
opacity: 1;
filter:alpha(opacity=100);
}

I'm assuming you're skipping through the video to hit the point where the script runs.
Using the Wistia .secondsPlaying() function, it only shows the actual number of seconds the user has played the video for.
The function you're looking for is .time(), which outputs the actual location of the user in the video, in seconds.
Try this:
<script>
var videoTrigger = false;
window._wq = window._wq || [];
_wq.push({ id: 'xxxxxxxx', onReady: function(video) {
video.bind("secondchange", function() {
if (video.time() >= 1830 && videoTrigger !== true) {
videoTrigger = true;
console.log("Run code here");
}
});
}});
</script>
Note that this code will also activate if the user skips past the activation point (as it uses >= and a variable instead of just ===).

Related

on scroll page with iframe inside iframe

I have a simple video player which is inserted into page within an iframe, now I want when the video player is visible play the video otherwise pause the video. to achieve that am using the intersection observer function.
Here is html skeleton
<body>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
<br/>
</body>
Here is js
var configFromParent = null;
window.addEventListener("message", function (event) {
var data = event.data;
if (data.action == "config") {
configFromParent = data;
}
var observer = new IntersectionObserver(function(entries) {
//console.log(entries);
if(entries[0]['isIntersecting'] === true) {
if(entries[0]['intersectionRatio'] === 1)
document.querySelector("#message").textContent = 'Target is fully visible in screen';
else if(entries[0]['intersectionRatio'] > 0.5){
$("#videoplayer")[0].play();
document.querySelector("#message").textContent = 'More than 50% of target is visible in screen';
}
else{
document.querySelector("#message").textContent = 'Less than 50% of target is visible in screen';
}
}
else {
$("#videoplayer video")[0].pause();
}
}, { threshold: [0, 0.5, 1] });
observer.observe(document.querySelector(".videoplayer"));
});
Now when scrolling my page nothing is happening, but when I change the parent src link to child iframe link everything works perfectly, but I want the iframe to be inside a parent iframe and when the video player is not visible pause the video otherwise play the video
What do I need to do solve this problem?
Observer is totally functional. https://codesandbox.io/s/loving-zhukovsky-chdds?file=/index.html this sandbox contains you html setup (not secure ofcourse). Scroll page down to see how message changes.
Secure frames behave in the same manner. You don't have to worry about it. But don't forget that IE may have no observer, you should handle it.
And I still assume that the problem in the post messaging

Detecting scroll event of Iframe called by AJAX reqest

i have a link in my main page that uses ajax to retrieve a PDF which is displayed in an Iframe, i am trying to detect scroll event of the PDF document and display a message or do something. i have tried different solutions from other solutions on stackoverflow and google search in general and couldn't find a good solution.
Main.php
<html>
<!--ajax request-->
<script type="text/javascript">
$(document).on('click','#nextpdf',function(event) {
event.preventDefault();
var reg = $(this).attr("href");
var str = reg.split('?')[1];
$.ajax({
type: "GET",
url: '../functions/pdfreader.php',
data: 'pdfxs='+str+'',
cache:false,
async: false,
success: function(data) {
// data is ur summary
$('.refresh').html(data);
return false;
}
});//end of ajax
});
</script>
<?php
while($obj = $c_content->fetch())
{
$title = $obj['lecture_title'];
echo '<article class="comment2">
//pdf link
<div class="comment2-body">
<div class="text" style="color:#999;padding-right:130px;">
<p><a href="../functions/pdfreader.php?'.$title.'""
style="color:#999" id="nextpdf">'.$title.'</a></p>
</div>
</div>
</article>
';
}
?>
</html>
pdfreader.php
//detect iframe pdf scroll
<script type="text/javascript">
$("myiframe").load(function () {
var iframe = $("myiframe").contents();
$(iframe).scroll(function () {
alert('scrolling...');
});
});
</script>
<?php
........
while($obj = $gettrend->fetch())
{
$coursefile = $obj['lecture_content'];
//this is my iframe
echo '<div class="mov_pdf_frame"><iframe id="myiframe"
src="https://localhost/einstower/e-learn/courses/pdf/'.$coursefile.'"
id="pdf_content"
width="700px" height="800px" type="application/pdf">
</iframe></div>';
}
?>
The major problem here is that nothing happens when i scroll the pdf document, how can i detect scrolling?
i found this fiddle that works but i cant view the javascript solution. http://fiddle.jshell.net/czw8pbvj/1/
First off, $("myiframe") isn't finding anything, so it attaches a load event to nothing. 1) change it to $("#myiframe") or $("iframe").
Here's a working fiddle (for iframe scroll detection)
UPDATE: to detect the scroll within PDF document, you can't use iframe. For that, you need embed or object tags AND a JS-enabled PDF document (hopefully its your PDFs..), who can send messages to your page's JS (see this answer).
Unfortunately, I couldn't find a scroll event in Adobe's Acrobat API Reference. It lists only these events:
Event type: Event names
App: Init
Batch: Exec
Bookmark: Mouse Up
Console: Exec
Doc: DidPrint, DidSave, Open, WillClose, WillPrint, WillSave
External: Exec
Field: Blur, Calculate, Focus, Format, Keystroke, Mouse Down, Mouse Enter, Mouse Exit, Mouse Up, Validate
Link: Mouse Up
Menu: Exec
Page: Open, Close
Screen: InView, OutView, Open, Close, Focus, Blur, Mouse Up, Mouse Down, Mouse Enter, Mouse Exit
So, basically, I think what you want just isn't possible as for now, at least with default rendering. With custom rendering (https://github.com/mozilla/pdf.js) it could be possible, though I'm not sure.
Apparently, it could be done with page scroll (see this issue). So back to iframes solution. :^D
Because this question is asked a long time ago, i think i need to help with my experience before.
The answer is: You can not
Why? because PDF is rendered by external apps, such as adobe pdf reader, foxit or else. And you can not attach event on them.
if you are using adobe reader, The only you can do is goto page, change zoom etc. Full example you can read here: https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf#page=8 (see. i bring you to page 8 directly instead to first page).
But, hei.. how if our client using another apps? we will confused more
The way to do this is only build your own pdf viewer.
we can using js library, like: http://www.bestjquery.com/2012/09/best-jquery-pdf-viewer-plugin-examples/
but here i only will show you to use pdf.js which created by mozilla.
main.php
<style>
.preview{
display:none;
width: 400px;
height: 400px;
border: 1px solid black;
}
</style>
file/test.pdf<br>
file/test1.pdf<br>
<div class="preview">
<iframe id="myiframe" frameborder="0" width="400px" height="400px" >not support iframe</iframe>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$(document).on('click', '#nextpdf', function(e){
e.preventDefault();
$('#myiframe').attr('src', $(this).attr('href'));
$('.preview').show();
});
//handle iframe on scroll
$('#myiframe').on('load', function () {
$(this).contents().scroll(function () {
console.log('scrolled');
}).click(function(){
console.log('clicked');
});
});
});
</script>
pdfreader.php
<?php
$path = 'file/';
$pdf = isset($_GET['pdfxs']) ? $path . $_GET['pdfxs'] : '';
if(!file_exists($pdf) || !mime_content_type($pdf) =='application/pdf') die('file not found');
?>
<div id="pdf-container">
<div id="pdf-box"></div>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
<script>
$(function(){
//original script : https://gist.github.com/fcingolani/3300351
function renderPDF(url, canvasContainer, options) {
var options = options || { scale: 1 };
function renderPage(page) {
var viewport = page.getViewport(options.scale);
var canvas = $(document.createElement('canvas'));
var renderContext = {
canvasContext: canvas[0].getContext('2d'),
viewport: viewport
};
canvas.attr('width', viewport.width).attr('height', viewport.height);
canvasContainer.append(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
renderPDF('<?=$pdf;?>', $('#pdf-box'));
});
</script>
Note: i put pdf on folder file/
in main.php you will notice that you can attach event scroll (and click too) to the pdf. because our pdf is not rendered by external apps now.
and the last part is, if you read pdfreader.php carefully, you will notice that you no need iframe anymore. You just need div, and then you can fully handle all event that do you want to your pdf : like scroll, click, change page, zoom, etc. why?? because your pdf is redered as canvas now (pdf.js render your pdf as HTML5 canvas). see full example of pdf.js
Please try this
iframe.on( "scroll", handler )
$("#frame").scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height())
alert('Bottom reached');
});
I found this in the JSFiddle that was referenced in the Fiddle you linked. The HTML field is empty. This CSS was in there, too.
body {
height: 1500px;
}
In the fiddle that you linked, the <iframe> has an ID of frame. I figured you can use the jQuery selector like $("#frame").
I think this will help you.
$("#myiframe").load(function () {
$(this).contents().scroll(function () {
//your code here
});
});

Video.js remove poster when using currentTime before video starts

I have a playlist of videos, with a list of each video in a sidebar. When I click on the name of the video I want to load in the sidebar, the player switches the current video to the one I just clicked.
Some videos have sections, and those sections need to start playing at a certain time in the video. For example, I have a video with 2 sections, Section 1 starts at 0:00, but when I click on "Section 2" in the sidebar, the video should start playing at 1:30 seconds into the video.
Now I got this working with the following code, but the poster image is still playing over the video when I click on Section 2 which should start playing in the middle of the video. How can I get rid of the poster image when starting a video with currentTime offset?
(function($) {
var current, gototime;
var istime = false;
// video.js object
var $player = videojs('ppi-video');
$('a').on('click', function(e) {
e.preventDefault();
var attr = $(this).attr('data-video');
var time = $(this).attr('data-time');
if(typeof time !== 'undefined' && time !== false) {
istime = true;
gototime = time;
}else {
istime = false;
gototime = undefined;
}
// If link has data-video attribute... continue
if(typeof attr !== 'undefined' && attr !== false) {
if( current == attr ) return;
var image_path = "images/screens/";
var content_path = "source/";
// Wait till player is ready
$player.ready(function() {
// Hide the player?
$("#ppi-video_html5_api").fadeOut(400, function() {
// Change poster
$("#ppi-video_html5_api").attr('poster', image_path + attr + ".jpg");
$player.poster(image_path + attr + ".jpg");
});
$player.src([
{ type: "video/mp4", src: content_path + attr + ".mp4" },
{ type: "video/webm", src: content_path + attr + ".webm" },
]);
// Set the currently playing variable
current = attr;
$("#ppi-video_html5_api").fadeIn();
});
}
});
function updateVideo() {
if( istime ) {
$player.currentTime(gototime);
$player.ready(function() {
/**
* Trying to get rid of poster here, but not working
*/
$("#ppi-video_html5_api").attr('poster', '');
$player.poster('');
$player.play();
});
}else {
$player.currentTime(0);
}
}
// update video when metadata has loaded
$player.on('loadedmetadata', updateVideo);
})(jQuery);
I found myself in the same situation where i needed to programmatically hide the poster image. (i wanted the posterimage to hide on drag of a custom scrubbar)
I found two ways that might help someone else who is in the same situation (i know this is an old post, but i came across it looking for an answer).
First and most simply you can hide the poster image using css:
.vjs-poster.vjs-poster.vjs-poster {
display: none;
}
// specificity bumped for default css, your mileage may vary.
However because i wanted this to be done on drag event i figured i might as well just use js:
player.posterImage.hide();
It looks like on Chrome and Firefox, setting currentTime() needs to be delayed a bit. What I did was call play() and then pause() to remove the poster before the video starts. Then I set a timeout of 200 milliseconds which has a callback which then calls currentTime().
Kind of a makeshift workaround but it is working nicely.

mediaelement.js - multiple videos on one page - > end and show poster when you start another one

I have multiple videos on a site (mediaelement.js)
When i play one, all others pause and end which is fine.
But i want to show also the poster again.
How can i do it?
for now i modified the pauseOtherPlayers (function) to set the time back to 0 but i want the poster to show not only the beginning.
// FOCUS: when a video starts playing, it takes focus from other players (possibily pausing them)
media.addEventListener('play', function() {
var playerIndex;
// go through all other players
for (playerIndex in mejs.players) {
var p = mejs.players[playerIndex];
if (p.id != t.id && t.options.pauseOtherPlayers && !p.paused && !p.ended) {
p.pause();
p.setCurrentTime(0);
}
p.hasFocus = false;
}
t.hasFocus = true;
},false);
Whats the function to show the poster?
poster.show(); somehow does not work
thx
//////////////////////////////////////////////////////////////////////////////////////////
ok figured it out myself.
heres the code if anyone interested:
success: function (mediaElement, domObject) {
mediaElement.addEventListener("pause", function(e){
// Revert to the poster image when ended
var $thisMediaElement = (mediaElement.id) ? jQuery("#"+mediaElement.id) : jQuery(mediaElement);
$thisMediaElement.parents(".mejs-inner").find(".mejs-poster").show();
});
}

Html5 video plays only for some times

Before I go into the problem I would like to say that this is the first time I'm trying to write javascript using OOP. So please bear with me and guide me if I doing anything wrong.
As title says I am using HTML5 video to play videos in my application and here is the code which I wrote.
I have created an object Screens where I have a video tag.
var Screens = {
getVideoScreen:function(){
return "<div id=\"celebration\"><video id=\"myvideo1\" width=\"300px\" ><source src=\"video/winning.mp4\" type=\"video/mp4\"></video></div> ";
},
getVideoElement:function() {
return $("#celebration");
}
};
This is an object where I actually control video.
var obj = Object.create(Screens);
obj.playVideo = (function() {
var videoFile = "";
var play = false;
function start() {
$("body").append(obj.getVideoScreen());
document.getElementById("myvideo1").play();
document.getElementById("myvideo1").addEventListener("ended",function(){
end(); console.log("end");
}, false);
}
function end() {
obj.getVideoElement().remove();
}
return {
startVideo:function(flag) {
play = flag;
if(play) {
start();
}
else {
end();
}
}
}
})();
I have a button and on click it plays video,
$("#start").click(function() {
obj.playVideo.startVideo(true);
});
This works fine for around 5 to 10 times and later on it doesn't work. Doesn't work mean I get a white screen and video doesn't play. I inspected the page and video tag is there but doesn't play the video. I really don't have any idea about what is going wrong. I saw few posts and that didn't help. Looking ahead for a help....
EDIT :
I am using chrome Version 26.0.1410.64 m. And I'm concerned only about this browser.
You can see this page.

Categories

Resources