On the Internet I found a jQuery code that works very well to open YouTube video in modal form. I change some dteails and everything was fine until I realized that do not recognize all the variations of YouTube URLs.
All I need is to extract the YouTube ID and put it in the right place. I wrote a regex and combined several versions but does not work with every URL.
This is my code:
$('a[href^="https://www.youtu"]').on('click', function(e){
var YouTube=$(this).attr('href').replace(/feature=player_embedded[&\w]*(?!['"][^<>]*>|<\/a>)/ig, "").replace(";", ""); // replace player_embedded
preg=/(?:http|https?:\/\/)?(?:www\.)?(?:youtu\.be\/|youtube\.com(?:\/embed\/|\/v\/|\/watch\?v=))([\w\-]{10,12})\b[?=&\w]*(?!['"][^<>]*>|<\/a>)/ig,
youtubeID=YouTube.replace(preg, '$1');
if (youtubeID!="" && (YouTube.indexOf('v') > -1 || YouTube.indexOf('embed') > -1))
{
// Prevent opening of external page
e.preventDefault();
// Variables for iFrame code. Width and height from data attributes, else use default.
var width = $(window).width(),
vidWidth = 800, // default
vidHeight = 450; // default
if ( $(this).attr('data-width') ) { vidWidth = parseInt($(this).attr('data-width')); }
if ( $(this).attr('data-height') ) { vidHeight = parseInt($(this).attr('data-height')); }
// responsive debug
var vidWidth = (width>vidWidth?800:(width-60));
var iFrameCode = '<div class="video-container"><iframe width="' + vidWidth + '" height="'+ vidHeight +'" scrolling="no" allowtransparency="true" allowfullscreen="true" src="https://www.youtube.com/embed/'+ youtubeID +'?controls=0&autohide=1&autoplay=1&iv_load_policy=3&theme=light&rel=0&showinfo=0" frameborder="0"></iframe></div>';
// Replace Modal HTML with iFrame Embed
$('#mediaModal .modal-body').html(iFrameCode);
// Set new width of modal window, based on dynamic video content
$('#mediaModal').on('show.bs.modal', function () {
// Add video width to left and right padding, to get new width of modal window
var modalBody = $(this).find('.modal-body'),
modalDialog = $(this).find('.modal-dialog'),
newModalWidth = vidWidth + parseInt(modalBody.css("padding-left")) + parseInt(modalBody.css("padding-right"));
newModalWidth += parseInt(modalDialog.css("padding-left")) + parseInt(modalDialog.css("padding-right"));
newModalWidth += 'px';
// Set width of modal (Bootstrap 3.0)
$(this).find('.modal-dialog').css('width', newModalWidth);
});
// Open Modal
$('#mediaModal').modal();
}
});
Thanks!
Related
I want to set the iframe height depending on the content height, here below code is working for local links, but i want to do it on dynamically.
please help.
<iframe id="frameDemo" src="https://myvook.blogspot.com"></iframe>
<script>
$(document).ready(function() {
$( "#frameDemo" ).on('load', function() {
var mydiv = $(this).contents().find("body");
var h = mydiv.height();
$("#frameDemo").height(h);
});
});
Following up with what Rory said, it's not possible to set the iframe height before before the iframe has been loaded since you'll be pulling content from another domain.
However, it is possible to set the height of the iframe after you've downloaded the content. Here is how I've tackled it:
function noteContentIframeLoaded(iframeId) {
// See http://stackoverflow.com/a/5788723 for how to implement this function
var iframeElement = $("#" + iframeId)[0];
setTimeout(function() {
setIframeHeight(iframeElement);
}, 10);
}
function setIframeHeight(iframe) {
if (iframe) {
if (iframe.contentWindow || iframe.contentDocument) {
var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
iframe.height = (iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight);
}
}
}
}
I want to know how I can open a series of urls in one tab. I have a list of urls, and I just want to open each one so its contents will be cached, just using one open tab so I don't end up with dozens of open tabs.
Use ** iframes ** one for each URL.
They can be made borderless using CSS if desired.
This is the my solution for your problem:
Html
<button onclick="changeURL()">
Change URL
</button>
Javascript
var listOfURL = ["https://www.google.es",
"https://www.stackoverflow.com",
"https://www.youtube.com"
];
var indexURL = 0;
var iframe = document.createElement("IFRAME");
function changeIndexURL() {
indexURL += 1;
if (indexURL >= listOfURL.length) {
indexURL = 0;
}
}
function changeURL() {
iframe.setAttribute("src", listOfURL[indexURL]);
iframe.style.width = 640 + "px";
iframe.style.height = 480 + "px";
document.body.appendChild(iframe);
changeIndexURL();
}
changeURL();
I'm trying to use a script in which I feature some tumblr video posts (those tagged with "featured" word) but I have two problems:
1) I don't know how set a size for the videos on the page (ideal 300 width). they are stuck on 400px.
2) I'd like the videos to grow to 1000px width, when people click play.
My tumblr is on cookjs.tumblr.com
can anyone help? thank you so much in advance!
<script>
if ($('p img').length > 0)
$(".textpost").css("overflow","hidden");
var rssurl = '/tagged/{text:Featured Tag}/rss';
$.get(rssurl, function(data) {
var $xml = $(data);
var vari = 0;
$xml.find("item").each(function() {
var $this = $(this),
item = {
title: $this.find("title").text(),
link: $this.find("link").text(),
description: $this.find("description").text(),
pubDate: $this.find("pubDate").text(),
author: $this.find("author").text()
}
vari = vari +1;
if(vari <4){
$('.featured-subhead').append('<section class=""><h2>
</h2>
<div class="">' + item.description + '</div><div class="">
Read More</div></section>');
}
});
});
</script>
So the right way of doing this is probably through the YouTube IFrame Player API. You'll be specifically interested in the onStateChange event listener. There's another way that I've done this that you may be interested in; here's the jQuery (since I was new to JS at the time):
$('iframe[src*="youtube.com"]').each(function(){
var videoURL = $(this).attr('src');
var videoID = videoURL.substr(videoURL.length - 11,11);
var thumbURL = 'http://img.youtube.com/vi/' + videoID + '/0.jpg';
$(this).wrap("<div class='video'></div>");
var videoDiv = $(this).parent();
videoDiv.css('background-image', 'url("' + thumbURL + '")').attr('id',videoID);
var heightUnit = $(this).height()*.25;
var widthUnit = $(this).width()*.20;
videoDiv.css('background-position', '0%, -' + heightUnit + 'px');
$(this).remove();
var playButton = $('<img />').attr({
'class': 'button',
'src':'playbutton.png'
}).css({
'width':widthUnit,
'margin-top': '-' + (widthUnit/2)*.783,
'margin-left': '-' + (widthUnit/2)
});
videoDiv.append(playButton);
playButton.on("click",function(){
$(this).css('opacity','0');
var newFrame = $('<iframe />').attr({
'src': 'http://www.youtube.com/embed/' + videoID + '?autoplay=1',
'frameBorder':'0'
});
videoDiv.append(newFrame);
});
});
What this is doing is grabbing the video url from each video on the page, removing the iframe and replacing it with the thumbnail (hosted by YouTube) and a separate clickable button. You can attach any handler you want to the button (even create your own button) but you'll also want to reload a new iframe with the embed url and append ?autoplay=1 to the end, which will start the video.
Here's a demo of this effect; something I coded a few years ago.
you can simply change the iframe height and width by using
function resizeIfrmae()
{
// your ifrmae id or you can pass id via function param
// resizeIfrmae(id) like this
$('#youtube_iframe_id').css('width','150');
$('#youtube_iframe_id').css('height','150');
}
onclick call this function
resizeIfrmae();
I want to embed a page developed by me using AngularJS into another third-party page (that may/may not be using AngularJS). To the third party it should be just as simple as adding a small piece of code - just like what they do to embed tweets from Twitter or add a comment box from Facebook.
I tried using <iframe>, but when my page is larger than iframe's size, scroll bars appear which I don't want. How to embed my page so that scroll bars don't appear and it appears that the embedded page is part of the original third-party website?
The embeddable page contains something similar to tweets/Fb comment box.
PS: Assume I have no control over the third-party sites.
PPS (to avoid the confusion): I control the content of the embeddable page i.e. I have control over what's there inside the iframe. But I don't have any control over the page where this iframe will be put. I need a piece of code (JS/html) which can be given to others so that after they add this piece of code, they will have my content in their page.
A very basic example, all credit goes to giveforward.com:
<script type="text/javascript" src="https://www.giveforward.com/widget.js">
</script>
<script type="text/javascript">
BuildWidget('c8c3');
</script>
the included javascript file simply defines a couple of functions and writes it's own iframe to the page.
function BuildWidget(fid)
{
makeFrame(fid);
}
function makeFrame(fid)
{
document.write('<iframe frameborder="0" scrolling="no" src="https://www.giveforward.com/widgets/w/'+fid+'/?m=1" style="min-width: 240px; width:100%; max-width:295px; height: 450px;margin:auto;display:block;"></iframe>');
}
function BuildAffiliateWidget(affid, packet) {
if(typeof packet == 'object')
{
refid = (typeof packet.refid == 'undefined') ? '' : '&refid=' + packet.refid;
category = (typeof packet.category == 'undefined') ? '' : '&category=' + packet.category;
title = (typeof packet.title == 'undefined') ? '' : '&title=' + encodeURIComponent(packet.title);
callback = (typeof packet.callback == 'undefined') ? '' : '&callback=' + packet.callback;
gfid = (typeof packet.gfid == 'undefined') ? '' : '&gfid=' + packet.gfid;
}else
{
refid = title = category = callback = gfid = '';
}
document.write('<iframe frameborder="0" scrolling="no" src="https://www.giveforward.com/widgets/a/?m=1&affid=' + affid + refid + category + title + callback + gfid + '" style="min-width: 240px; width: 100%; max-width:295px; height:450px;margin:auto;display:block;" class="affiliate_iframe"></iframe>');
}
The url that the iframe points to can be the same url that you are having your users embed to their own iframe now.
Thanks to #TheGunner for pointing me in the right direction. But he didn't specify the resizing part. So if the embedded page is bigger than the iframe then scroll bars would appear. To prevent this, you can call window.PostMessage from the embeddable page and the listener will take care of the resizing part.
I have created a script which assigns dynamic id to the iframe, and this id is used later to resize.(My script takes care only the height of the iframe. If the embeddable page is responsive, width shouldn't be a problem).
Here is the content of widget.js (this contains the window.PostMessage listener and the code to create iframe):
(function() {
var func = function(e){
if (e.data.indexOf('iid:') === 0) {
var hashPos = e.data.indexOf('#');
var iid = e.data.substring('iid:'.length, hashPos);
var height = e.data.substring(hashPos + 1) + 'px';
document.getElementById(iid).style.height = height;
}
};
var old = window.onmessage;
if (typeof window.onmessage != 'function') {
window.onmessage = func;
} else {
window.onmessage = function (e, f, g, h) {
if (old) {
old(e, f, g, h);
}
func(e);
};
}
}());
var BuildWidget = function(url, width) {
var getNewIid = function() {
return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
return v.toString(16);
});
};
var iid = getNewIid();
if(!width) {
width = 900;
}
var maxWidth = width + 'px';
document.write('<iframe id="' + iid + '" src="' + url + '?iid=' + iid + '" frameborder="0" scrolling="no" style="min-width: 300px; width:100%; max-width:' + maxWidth + '; display:block;"></iframe>');
};
var AddXWidget = function(width) {
var url = 'http://localhost:8080/embed';
BuildWidget(url, width);
};
Now give out the following script to third-party sites to enable them to embed your widget:
<script type="text/javascript" src="http://path/to/widget.js">
</script>
<script>
AddXWidget(400);
</script>
Now, the embeddable page(the page inside iframe) should call window.PostMessage() as follows:
window.top.postMessage('iid:' + iid + '#' + elem.scrollHeight, '*');
Here iid is the URL parameter iid obtained and elem is the element looked up using document.getElementById()
Hi Stack Overflow Community.
I have a problem. I have a process with an iFrame.
This process have some Javascript to set iFrame height based on iFrame content. I think its not enough, so I decided to make an automatic resize of the iFrame height based on content changes without reloading any iFrame or process. Unfortunately, I tried but was unable to due to doubts. I searched everywhere in Stack Overflow but I didn't found the solution.
Rules:
Auto Height resize in the iFrame.
No reloads in the parent window or iFrame.
No triggers, no Interval.
Just everything automatic.
Window and iFrame are in the same domain.
Could you please help me?
Thanks, and sorry for bad english.
My Actual CODE:
if(document.getElementById("frame") != undefined)
{
var frame = document.getElementById("frame");
$(frame).load(function(){
var frame_height = frame.contentWindow.document.body.scrollHeight + 'px';
frame.setAttribute('style', 'height:' + frame_height + ' !important');
console.log('its this loading?');
contentBasedIframeResize(); //this is worthless, just testing. isn't dynamic right now. need fix.
// As soon as the frame finish the load, this frame height will be based in the frame content
});
function contentBasedIframeResize()
{
var add_button = $(frame).contents().find(".some_obj"); //preparing the trigger
var remove_button = $(frame).contents().find(".some_obj"); //preparing the trigger
if(add_button != undefined)
{
$(add_button).click(function(){
var add_height = frame.contentWindow.document.body.scrollHeight + 'px';
frame.setAttribute('style', 'height:' + add_height + ' !important');
});
}
if(remove_button != undefined)
{
$(remove_button).click(function(){
var remove_height = $("#frame").contents().find("#table_obj").height();
remove_height = parseInt(remove_height) + 100; //hardcoded
frame.setAttribute('style', 'height:' + remove_height + 'px !important');
console.log("its this working v2?");
});
}
}
}
Try this,
function resizeIframe(obj)
{
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
$('iframe').load(function(){
resizeIframe(this);
});