Random iframe on page load - javascript

I have a few iframes on my homepage at the bottom (http://www.binarycontrast.com), where one is randomly selected on page load. The code I'm using below works, but the iframes load really slowly. What the code does is generate a random iframe to display on page load. I actually got the code from another question on here regarding loading random images on page load, and I just tweeked it to what I needed.
If I have a single iframe on the page it loads really quickly, but for some reason using this code slows it down a lot, so I want a way to speed up the iframe loading time whilst using some script to randomly choose one to display.
An alternative method or help with the code I have would be really appreciated.
Please see the below code:
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/24Option" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/OptionFair" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
<iframe class="random-iframe" src="http://www.binarycontrast.com/visit/StockPair" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>
And the script used to make it work:
$(window).load(function(){
var divs = $("iframe.random-iframe").get().sort(function(){
return Math.round(Math.random())-0.5; //random so we get the right +/- combo
}).slice(0,1)
$(divs).appendTo(divs[0].parentNode).show();
});
And the css:
iframe.random-iframe { display: none; }
Thanks for any help in advance.

I think the Problem ist that you load all the iframes.
Even the ones you don't need.
You should only hold your Urls (Not the whole iframe tags) and the make a random select for one of the urls.
Only then create a Iframe tag with the selected url.
something like this:
function getRandomUrl(urls) {
var minIndex = 0;
var maxIndex = urls.length - 1;
var randomIndex = Math.floor(Math.random() * (maxIndex - minIndex)) + minIndex;
return urls[randomIndex];
}
var urls = [
"url1",
"url2",
"url3"];
var randomSelectedUrl = getRandomUrl(urls);
$("#hereComesTheIframeInto").html(
"<iframe class='random-iframe' src='" + randomSelectedUrl + "' width='100%' height='700' frameborder='0' scrolling='yes' seamless='seamless'></iframe>");
<div id="hereComesTheIframeInto"></div>
I Hope you get the point. I didn't finish it completely for you.
EDIT:
eradicated error. (I have composed the strings with "&" before but in Javascript you have to do this with "+")
Sorry for this. =(

Instead of loading all the iframes, and then hiding some of them, try to generate only one iframe.
Use random to chose which url will be in the src.
Then use
var chosenURL = 'url'; // The url you randomly chose
var parentNode = 'iframe-container'; // Where you want to put your iframe
$('<iframe class="random-iframe" src="'+chosenURL+'" width="100%" height="700" frameborder="0" scrolling="yes" seamless="seamless"></iframe>').appendTo(parentNode);

You would be far better of using your code to insert one of three urls randomly into the iframes src.

Looks like there are two issues:
You're hiding the iframes but they're all still loading in the background. You could try using an array with the sources and just creating a single iframe element, or leaving the src tag blank until you're ready to load it.
You're waiting for the window to load, including all images and iframes, before showing any iframe. If you changed the code to run when the document is ready then the code will run much sooner. Better yet, as long as the script is placed after the iframes in the DOM, you don't even need to wait for the whole document to load.
function loadRandomIFrame() {
var divs = document.querySelectorAll(".random-iframe"),
div = divs[Math.round(Math.random() * (divs.length - 1))],
frame = document.createElement("iframe");
frame.width = "100%";
frame.height = 700;
frame.frameborder = 0;
frame.scrolling = "yes";
frame.seamless = "seamless";
frame.src = div.dataset.src;
div.parentNode.appendChild(frame);
}
loadRandomIFrame();
<div class="random-iframe" data-src="http://www.binarycontrast.com/visit/24Option"></div>
<div class="random-iframe" data-src="http://www.binarycontrast.com/visit/OptionFair"></div>
<div class="random-iframe" data-src="http://www.binarycontrast.com/visit/StockPair"></div>

Related

Read iFrame content with Jquery (iFrame loads more ajax in itself)

I have a video player I implement with an iFrame.
<iframe
src="//player.twitch.tv/?video=v209807471&autoplay=true&time=02h59m45s"
frameborder="0"
scrolling="no"
allowfullscreen="true"
id="tFrame"
class="ls-vod-iframe"
>
</iframe>
I would now like to read the current timestamp which is located in the .player-seek__time span inside this iframe.
When I check the source code of //player.twitch.tv/?video=v209807471&autoplay=true&time=02h59m45s if shows me an empty div of #video-playback so I assume it loads the contents in another call internally.
I tried it with this:
var $playerBody = $('#tFrame').contents().find('#video-playback');
var $ts = $playerBody.find('.player-seek__time');
console.log($ts);
but $ts.length is 0.
Is there another way to get the content of .player-seek__time or is anything wrong with the above code in general?
getTimeStamp = function() {
var frameDoc = document.getElementById('tFrame').contentDocument;
if (frameDoc) {
return frameDoc.body.querySelector('#video-playback > .player-seek__time').textContent;
}
else {
return false; //maybe access is blocked by the website
}
}
document.getElementById('tFrame').addEventListener('load', function() {
alert(getTimeStamp());
});
<iframe
src="//player.twitch.tv/?video=v209807471&autoplay=true&time=02h59m45s"
frameborder="0"
scrolling="no"
allowfullscreen="true"
id="tFrame"
class="ls-vod-iframe"
>
</iframe>
This should work in general but it seems that twitch won't allow you to load their site inside an iframe?
Also same-origin-policy could prevent an access.
For me it only works when using this code via the console inside a tab.

How can I check that if img src start with http://img.youtube.com/vi/ and after any character and replace with a youtube video iframe?

So basically I would like to make a little lazy load code to my site.
Every Youtube video has a thumbnail and usually the url is something like this:
http://img.youtube.com/vi/<THEVIDEOID>/maxresdefault.jpg
I would like to detect this and if it's true, this can be a click event, and after you clicked the image, you get the iframe and you can play the video.
Now, I know there is thousand and thousand outsiders plugin in the internet, but I don't want to load any other code, just that function what is really necessary for this script to work (I hate big load times like anyone else).
Sometimes the outside plugins has thousand, and thousand unnecessary functions for me, like check on every load I chose the click method or the scroll method, and other not useful things.
That's why I decided I trying to build my own.
I saw this post in the search results, but I would like to build this on jQuery way.
Note:
This need for a Wordpress site, that's why I use jQuery instead of $.
This what I have now:
jQuery(document).ready(function() {
function youtubecheck(){
var myregexp = /[a-z,A-Z,0-9]/g;//Regexp for videoid
var imageurl="http://img.youtube.com/vi/"+myregexp+"/maxresdefault.jpg"; // This doesn't sounds right, I need to find out something else.
if (jQuery("img").attr("src")=== "imageurl"){
var autoplay="?autoplay=1/"//this for iframe
jQuery(this).addClass("YT-image"); // Obviously we need class, because we don't whant to do this with all images, just with YT-imgaes.
jQuery(".YT-image").click(function() {
jQuery(".YT-image").replaceWith('<iframe width="560" height="315" src="https://www.youtube.com/embed/'+myregexp+autoplay+'" frameborder="0" allowfullscreen></iframe>'); // maybe we need each for every image? Also I'm not sure about "myregexp" variable in here.
});
}
}
youtubecheck();
});
Changed your if condition and regex
jQuery(document).ready(function() {
function youtubecheck() {
if (/img\.youtube\.com\/vi\/[a-z,A-Z,0-9]+\/maxresdefault\.jpg/g.test(jQuery("img").attr("src"))) {
var videoId = /img\.youtube\.com\/vi\/(.*?)\/maxresdefault\.jpg/g.exec(jQuery("img").attr("src"))[1];
var autoplay = "?autoplay=1/"; //this for iframe
jQuery("img").addClass("YT-image"); //Obviously we need class, becouse we don't whant to do this with all images, just with YT-imgaes.
jQuery(".YT-image").click(function() {
jQuery(this).replaceWith('<iframe width="560" height="315" src="https://www.youtube.com/embed/' + videoId + autoplay + '" frameborder="0" allowfullscreen></iframe>'); // maybe we need each for every image? Also I'm not sure about "myregexp" varible in here.
});
}
}
youtubecheck();
});
Updated the code this works

Iframe/href difficulties

In short, we have a page with an iframe, and I want to target the page URL dynamically.
For simplicity, the page is located at http://1/2/3.aspx
The iframe would be on the 3.aspx page, and the iframe points to a completely different URL, let's say http://100/101/102.html
I want to target the iframe to go to http://1/2/"some URL"
A coworker suggested inline javascript using window.location.parent, but I can't figure out how to implement this. Using the usual ../ in the link's href tag only results in me navigate up within the frame's context (to 101, 100, so on).
As always, thank you to the community for your time.
EDIT: I would like to use inline javascript for this if at all possible.
I guess you mean something like this
<iframe id="ifr" src=""></iframe>
<script>
document.getElemenById("ifr").src = "http://1.2.3/page.html";
</script>
Update
To use location data from the iframe's parent, you can do like this
<iframe id="ifr" src=""></iframe>
<script>
var parenturl = parent.location.href;
var newurl = parenturl.replace("from-this","to-this");
document.getElemenById("ifr").src = newurl;
</script>

javascript frame navigation in ie11 with a pdf

I have a simple web page where 1 frame displays a pdf and another a menu bar.
<iframe src="bar.html" name="menu" ></iframe>
<iframe src="doc.pdf" name="itempane" ></iframe>
Using chrome I can navigate from the menu bar to the parent and back down to the frame containing the pdf in order to print it
var pWindow = window.parent;
pWindow['itempane'].print();
Attempting to do the same in IE11 gives an Invalid calling object error.
you can see this at http://www.abhrdev.co.uk/main.html
What am I doing wrong / what is IE doing differently?
Cheers
Updated.....
I think I have proved that this is not a javascript coding issue but related to the pdf handling in IE. With the following page
Print PDF<br/>
Print HTML
<iframe src="bar_1.html" name="menu" ></iframe>
<iframe src="doc.pdf" name="pdfpane" ></iframe>
<iframe src="doc.html" name="htmlpane" ></iframe>
and this function
function printFromMain(paneName) {
var pWindow = window[paneName];
pWindow.focus();
pWindow.print();
}
the printing of the html page works but not the pdf the pWindow.focus() gives Invalid Calling Object - any insight into why that might be greatfully recieved
After trying several things, I finally go this to work in IE11:
1) use an object tag instead of iframe
2) run focus() / print() directly on the element
3) run after a timeout, to make sure everything in is loaded. There may be a better way (like using some event listener) to do this, as the timeout time needs to be fairly long for it to work properly
setTimeout(function () {
var contentThingy = document.getElementById('itempane');
contentThingy.focus();
contentThingy.print();
}, 4000);
Object (with a specified id) instead of iframe:
<object id="itempane" ... ></object>
Note: doesn't work in chrome. One of the other variations in the other answers (i.e. using ContentWindow) may.
Try actually using the window.frames to get the frameList and reference it by the frame name that way.
var pWindow = window.parent; //reference the parent from the iframe
var ifr = pWindow.frames.itempane; //get the pdf frame from the frame list
ifr.focus();
ifr.print();
Try this
<iframe src="bar.html" name="menu" ></iframe>
<iframe src="doc.pdf" ID="itempane" ></iframe>
var otherPane = parent.document.getElementById("itempane");
otherPane.focus(); // OR
otherPane.print(); // OR
var doc = otherPane.contentWindow || otherPane.contentDocument;
doc.focus();
doc.print();

How to stop video from playing in hidden DIV

Here is the JavaScript:
function unhide(divID) {
var item = document.getElementById(divID);
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
}
}
Here is the HTML:
<a href="javascript:unhide('verizon');">VERIZON<br>
SAP<br>
<div id="sap" class="hidden">
<embed src="videos/sap.mov" height="270" width="480" scale="tofit"></embed>
</div>
<div id="verizon" class="hidden">
<embed src="videos/verizon.mov" height="270" width="480" scale="tofit"></embed>
</div>
When I click on SAP the video plays. When I click on Verizon it also plays but the SAP video continues to play even though it is hidden.
I am very new to javascript.
Is there a better way to do this? How do I fix with the code I already have?
You could do something like this:
function unhide(divID) {
var item = document.getElementById(divID);
var other = {"verizon":"sap","sap":"verizon"};
if (item) {
item.className=(item.className=='hidden')?'unhidden':'hidden';
var tar = document.getElementById(other[divID]);
tar.className = 'hidden';
tar.getElementsByTagName("embed")[0].stopVideo();
}
}
Other is just an object which provides easy access to the id of the video to be stopped. It uses the string from divID to obtain the other string.
Then once you have that other element, you traverse into its children to find the embed element. [0] is used to get the first matching element (your video). Then you can use javascript's stopVideo() method on it to stop the video.
My preferred solution would be to set the HTML of that div to null rather than try to manipulate what's inside it to get it to shut up. After all it's hidden so why bother keeping it there.
document.getElementByID('div').innerHTML = "";
Thereby completely removing anything in there.
And to un-hide it (note you may have to fidget with this a bit to get the quotes to behave)
document.getElementByID('div').innerHTML = '<embed src="videos/sap.mov" height="270" width="480" scale="tofit"></embed>';
I think for flash or a heavy element like a video player this would be a better solution, imagine a page with 30 of these that are hidden, it would get pretty bogged down.

Categories

Resources