How to add start time variable to Lite YouTube Embed code created by Amit Agarwal - youtube

I use Amit Agarwal code from https://www.labnol.org/internet/light-youtube-embeds/27941/ in my website to lite embeded youtube video.
Is there any way to add start time to the script so that I could load each video with different start time.
<div class="youtube-player" data-id="VIDEO_ID" start-id="TIME"></div>
His complete script are as follows:
<script>
function labnolIframe(div) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?autoplay=1&rel=0');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '1');
iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
div.parentNode.replaceChild(iframe, div);
}
function initYouTubeVideos() {
var playerElements = document.getElementsByClassName('youtube-player');
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var div = document.createElement('div');
div.setAttribute('data-id', videoId);
var thumbNode = document.createElement('img');
thumbNode.src='//i.ytimg.com/vi/ID/hqdefault.jpg'.replace('ID', videoId);
div.appendChild(thumbNode);
var playButton = document.createElement('div');
playButton.setAttribute('class', 'play');
div.appendChild(playButton);
div.onclick = function () {
labnolIframe(this);
};
playerElements[n].appendChild(div);
}
}
document.addEventListener('DOMContentLoaded', initYouTubeVideos);
</script>
I have added timeId var into the mix hoping that I could use start-id value to let embed video to start at specific time. It still start at 0 sec of the video.
function labnolIframe(div) {
var iframe = document.createElement('iframe');
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?start='+ div.dataset.id + '&autoplay=1&rel=0');
iframe.setAttribute('frameborder', '0');
iframe.setAttribute('allowfullscreen', '1');
iframe.setAttribute('allow', 'accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture');
div.parentNode.replaceChild(iframe, div);
}
function initYouTubeVideos() {
var playerElements = document.getElementsByClassName('youtube-player');
for (var n = 0; n < playerElements.length; n++) {
var videoId = playerElements[n].dataset.id;
var timeId = playerElements[n].dataset.id;
var div = document.createElement('div');
div.setAttribute('data-id', videoId);
div.setAttribute('start-id', timeId);
var thumbNode = document.createElement('img');
thumbNode.src = '//i.ytimg.com/vi/ID/hqdefault.jpg'.replace('ID', videoId);
div.appendChild(thumbNode);
var playButton = document.createElement('div');
playButton.setAttribute('class', 'play');
div.appendChild(playButton);
div.onclick = function () {
labnolIframe(this);
};
playerElements[n].appendChild(div);
}
}
document.addEventListener('DOMContentLoaded', initYouTubeVideos);

Just change:
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?autoplay=1&rel=0');
to:
iframe.setAttribute('src', 'https://www.youtube.com/embed/' + div.dataset.id + '?start=YOUR_START_TIME_IN_SECONDS&autoplay=1&rel=0');
Note the added start=YOUR_START_TIME_IN_SECONDS& in the URL.

Related

How to implement midroll ad with MediaElements.JS?

How to implement midroll ad with MediaElements.JS?
I made preroll and I hahe question here too.
How to start ad after I press play button of original video?
I thought maybe there are some controls or whatever for ads, but I didn't find it.
Here is my code:
$('iframe').attr('allowfullscreen', '');
$("iframe, object").each(function(i) {
var thisYT = $(this);
if (thisYT.is("iframe")) {
var src = thisYT.attr('src');
} else {
var src = thisYT.attr('data');
}
var width = thisYT.attr('width');
var height = thisYT.attr('height');
var YTID = getId(src);
if (YTID != "error") {
thisYT.replaceWith('<video id="' + YTID + '" width="' + width + '" height="' + height + '" controls="control" preload="none"><source src="https://www.youtube.com/watch?v=' + YTID + '" type="video/youtube" /></video>');
}
var player = new MediaElementPlayer(YTID, {
playsinline: true,
features: ['playpause','current','progress','duration','volume','fullscreen','vast'],
vastAdTagUrl: 'url',
adsPrerollAdEnableSkip: 4,
adsPrerollAdSkipSeconds: 10,
success: function(mediaElement, originalNode, instance) {
console.log(mediaElement, originalNode, instance);
}
});
});
function getId(url) {
var regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
var match = url.match(regExp);
if (match && match[2].length == 11) {
return match[2];
} else {
return 'error';
}
}
You need to install ad plugin for mediaelement.js for having required features for preroll and midroll Follow the instructions for using below repositiory
https://github.com/mediaelement/mediaelement-plugins/blob/master/docs/ads.md

HTML2Canvas creating multiple divs

I'm trying to create a PDF using jsPDF and HTML2Canvas.
I have multiple DIVs to insert into the PDF.
If I try to put all DIVs into a container and render once then it only puts the first page height into the PDF.
Can't figure out how to render multiple divs and stick them in the same PDF so that it keeps going page by page.
JAVASCRIPT
function genPDF() {
html2canvas(document.getElementById("container"), {
onrendered: function (canvas) {
var img = canvas.toDataURL();
var doc = new jsPDF();
doc.addImage(img, 'PNG');
doc.addPage();
doc.save('test.pdf');
}
});
}
HTML
<div id="container">
<div class="divEl" id="div1">Hi <img src="img1.JPG"> </div>
<div class="divEl" id="div2">Why <img src="img2.PNG"> </div>
</div>
<button onClick="genPDF()"> Click Me </button>
Add each of your images separately.
You need to wait for all the html2canvas renderings are done and added to pdf and then save your final pdf.
One way to achieve this by using JQuery and array of promises, actual code would look like this:
function genPDF() {
var deferreds = [];
var doc = new jsPDF();
for (let i = 0; i < numberOfInnerDivs; i++) {
var deferred = $.Deferred();
deferreds.push(deferred.promise());
generateCanvas(i, doc, deferred);
}
$.when.apply($, deferreds).then(function () { // executes after adding all images
doc.save('test.pdf');
});
}
function generateCanvas(i, doc, deferred){
html2canvas(document.getElementById("div" + i), {
onrendered: function (canvas) {
var img = canvas.toDataURL();
doc.addImage(img, 'PNG');
doc.addPage();
deferred.resolve();
}
});
}
For me it works like that:
$('#cmd2').click(function () {
var len = 4; //$x(".//body/div/div").length
var pdf = new jsPDF('p', 'mm','a4');
var position = 0;
Hide
for (let i = 1;i <= len; i++){
html2canvas(document.querySelector('#pg'+i),
{dpi: 300, // Set to 300 DPI
scale: 1 // Adjusts your resolution
}).then(canvas => {
pdf.addImage(canvas.toDataURL("images/png", 1), 'PNG', 0,position, 210, 295);
if (i == len){
pdf.save('sample-file.pdf');
}else{
pdf.addPage();
}
});
}
});
You could try this, using the follwing javascript references in the HTML. Html2Canvas and jsPDF are quite picky with versions you use.
https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"
https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js"
var forPDF = document.querySelectorAll(".js-panel-pdf");
var len = forPDF.length;
var thisPDF = new jsPDF('p', 'mm', [240, 210]); //210mm wide and 297mm high
for (var i = 0; i < forPDF.length; i++) {
html2canvas(forPDF[i], {
onrendered: function(canvas) {
thisPDF.addImage(canvas.toDataURL("images/png", 1), 'PNG', 0, 0, 210, 295);
if (parseInt(i + 1) === len) {
thisPDF.save('sample-file.pdf');
} else {
thisPDF.addPage();
}
}
});
}
Stuart Smith - This is not working it does not allow to download the pdf
here is java script code
function generatePDF(){
var imgData;
var forPDF = document.querySelectorAll(".summary");
var len `enter code here`= forPDF.length;
var doc =new jsPDF('p','pt','a4');
for (var i = 0; i < forPDF.length; i++){
html2canvas(forPDF[i],{
useCORS:true,
onrendered:function(canvas){
imgData = canvas.toDataURL('image/jpg',1.0);
var doc =new jsPDF('p','pt','a4');
doc.addImage(imgData,'jpg',10,10,500,480);
if (parseInt(i + 1) === len) {
doc.save('sample-file.pdf');
} else {
doc.addPage();
}
}
});
}
}

Images gets truncated after setting SRC Value (iOS)

I ran into a strange limitation from iOS/Safari/Chrome.
The user can select an image and it filecontent gets pasted into a input element.
The Length of the both are unequal. Is this an iOS limitation?
L.users.importConfigurations = function(options) {
var target = null;
this._getInputFileElement = function() {
var that = this;
fileInput = $('<input type="file" accept="image/*" style="display:none;" capture="camera" />');
fileInput.change(function() {
that._handleFiles(fileInput);
});
return fileInput;
};
this.showFileSelectionDialog = function() {
var fileInput = this._getInputFileElement();
fileInput.click();
};
this._handleFiles = function(fileInput) {
var files = fileInput[0].files;
if (files && files.length) this._readFile(files[0]);
};
this._readFile = function(fileInfo) {
var that = this;
var reader = new FileReader();
reader.onload = function(e) {
that._uploadFile(e.target.result);
};
reader.readAsDataURL(fileInfo);
};
this._uploadFile = function(fileData) {
var fbValue = $(options.target).closest('.fileboxframe').find(".fileboxvalue");
if (fbValue && fbValue.length > 0) {
alert("Length before: " + fileData.length.toString());
fbValue.attr('src', fileData);
alert("Length after (Should be same): " + fileData.length.toString());
alert("Length after (Should be same): " + fbValue.attr("src").length.toString());
}
};
this.showFileSelectionDialog();
};
https://jsfiddle.net/ChristophWeigert/81qu41L5/
I found an answer in this topic:
Why is the default max length for an input 524288?
Solution was to use a textare and not a textbox.

Turbolinks not rendering code on page change

I'm using Segment.io to do tracking on my site. We have a live chat widget that I'd like to be displayed on every page. However I'm unable to figure out how to make this work.
I've created an analytics.js which loads in the body (I've also tried adding the analytics.page(); to the body without any results):
window.analytics = window.analytics || [];
window.analytics.methods = ['identify', 'group', 'track',
'page', 'pageview', 'alias', 'ready', 'on', 'once', 'off',
'trackLink', 'trackForm', 'trackClick', 'trackSubmit'];
window.analytics.factory = function(method){
return function(){
var args = Array.prototype.slice.call(arguments);
args.unshift(method);
window.analytics.push(args);
return window.analytics;
};
};
for (var i = 0; i < window.analytics.methods.length; i++) {
var key = window.analytics.methods[i];
window.analytics[key] = window.analytics.factory(key);
}
window.analytics.load = function(key){
if (document.getElementById('analytics-js')) return;
var script = document.createElement('script');
script.type = 'text/javascript';
script.id = 'analytics-js';
script.async = true;
script.src = ('https:' === document.location.protocol
? 'https://' : 'http://')
+ 'cdn.segment.io/analytics.js/v1/'
+ key + '/analytics.min.js';
var first = document.getElementsByTagName('script')[0];
first.parentNode.insertBefore(script, first);
};
window.analytics.SNIPPET_VERSION = '3.1.0';
window.analytics.load('kYDWuP6nxI');
window.analytics.page();
document.addEventListener("turbolinks:load", function() {
console.log('page change');
analytics.page();
});
When I visit a new page on the app it shows the console log, but analytics.page(); doesn't seem to be rendered except when I do a manual page refresh.
Anybody know how to fix this?

Using itextsharp and MVC to display a range of PDF pages in a web page

I used this site to copy examples and to ask help from various people so I thought I would share my attempt at putting things together with others who might be interested.
The following takes a range of pages from an existing PDF file and displays the result in an iframe or a new Tab. It uses [itextsharp][1]
The code contains a fair amount of novice code but at least it works.
There is absolutely no point point in asking me any questions because I almost certainly will not know the answer.
If anyone would like to point out where improvements might be made, I would be very grateful.
VIEW
<input id="btnIframe" type="button" value="Iframe" />
<input id="btnNewTab" type="button" value="New Tab" />
<div id="pdfDiv"></div>
<script type="text/javascript">
$(function () {
$("#btnIframe").click(function () {
var filename = "Test1";
var startPage = 1;
var endPage = 3;
var pParams = filename + "¬" + startPage + "¬" + endPage;
var url = '/PDFTest/GetPdfPages/' + pParams;
var html = "<iframe src=" + url + " style='width: 100%; height: 400px' ></iframe>";
$('#pdfDiv').html(html);
});
$("#btnNewTab").click(function () {
var filename = "Test1";
var startPage = 1;
var endPage = 3;
var pParams = filename + "¬" + startPage + "¬" + endPage;
var url = '/PDFTest/GetPdfPages/' + pParams;
window.open(url, "_blank");
});
});
</script>
CONTROLLER
public FileStreamResult GetPdfPages(string id)
{
var pParams = id.Split('¬');
var fileName = pParams[0];
var start = Convert.ToInt32(pParams[1]);
var end = Convert.ToInt32(pParams[2]);
var inputFile = Server.MapPath(#"~/PDFFiles/" + fileName + ".pdf");
var inputPdf = new PdfReader(inputFile);
int pageCount = inputPdf.NumberOfPages;
if (end < start || end > pageCount)
{
end = pageCount;
}
var inputDoc =
new Document(inputPdf.GetPageSizeWithRotation(1));
using (MemoryStream ms = new MemoryStream())
{
var outputWriter = PdfWriter.GetInstance(inputDoc, ms);
inputDoc.Open();
var cb1 = outputWriter.DirectContent;
for (var i = start; i <= end; i++)
{
inputDoc.SetPageSize(inputPdf.GetPageSizeWithRotation(i));
inputDoc.NewPage();
var page =
outputWriter.GetImportedPage(inputPdf, i);
int rotation = inputPdf.GetPageRotation(i);
if (rotation == 90 || rotation == 270)
{
cb1.AddTemplate(page, 0, -1f, 1f, 0, 0,
inputPdf.GetPageSizeWithRotation(i).Height);
}
else
{
cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
inputDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "inline;test.pdf");
Response.Buffer = true;
Response.Clear();
Response.OutputStream.Write(ms.GetBuffer(), 0, ms.GetBuffer().Length);
Response.OutputStream.Flush();
Response.End();
return new FileStreamResult(Response.OutputStream, "application/pdf");
}
}

Resources