I am currently trying to run a function when all iframes on the page are loaded. I am using jQuery, but it only works when there is one iframe on the page. Once I start having mutiple iframes my functionality stops working. Here is the code im working with:
$('iframe.preview-iframe').on( 'load', function() {
$('iframe.preview-iframe').contents().find('section[rowposition] a').each(function(){
// Append a span tag with the href of the according content a tag
$(this).append('<span style="position:absolute;left:0;color:red;background:yellow;">' + $(this).attr('href') + '</span>');
});
});
Do I need to write a loop that looks over how many iframes I have and then only run the script once the last iframe is loaded or is there some other way to do it?=
You can do something like the following:
Get all the iframes elements in a variable
Loop through each of the iframes and if all of them are loaded, execute your required code.
$(window).on('load', function() {
var iframes = $('iframe');
var loaded = 0;
iframes.each(function() {
$(this).on('load', function() {
loaded++;
if (loaded == iframes.length) {
// run your code here
$('iframe').each(function() {
$(this).contents().find('section[rowposition] a').each(function() {
// Append a span tag with the href of the according content a tag
$(this).append('<span style="position:absolute;left:0;color:red;background:yellow;">' + $(this).attr('href') + '</span>');
});
});
}
});
});
});
Related
I have a script that converts youtube links to working iframes when loaded automatically, once the user clicks the element with a preloaded thumbnail, it then generates a watchable iFrame. The main part of the code works, but its not wanting to work when told to run after the element is clicked. The code below im trying to get to run removes any content in the 'scr' url containing '&' and after.
The thumbnail element when clicked, loads the iframe: .youtube-box
The iframe called after when clicking .youtube-box:
<iframe class="youtube-frame" src="http://www.youtube.com/embed/qYTT-0A8QIE&list=PLbfa3OWXAjLMk5PKV2KDaRveQt8BntMK5&t=4s&index=13?rel=0;&autoplay=1&vq=hd720" style="height: 622px;"></iframe>
My code:
$(window).on("load", function(){
$(".youtube-box").click(function () {
setTimeout(function(){
jQuery('iframe').attr('src',function(i,v){
return v.split('&')[0]; // get the string part before the `?`
// or
// return v.replace(/\?.*/,'');
});
}, 2000);
});
});
What it is suppose to remove:
&list=PLbfa3OWXAjLMk5PKV2KDaRveQt8BntMK5&t=4s&index=13?rel=0;&autoplay=1&vq=hd720
This is a tempoary fix, but not an absolute solution I found, basically I just added on to the script that turns the element to an iframe
<script>
$(window).on("load", function(){
$(function() {
$('a[href^="https://www.youtube.com/watch"]').each(function() {
var yt_url = this.href,
yt_id = yt_url.split('?v=')[1],
yt_title = $(this).text();
$(this).replaceWith('<div class="youtube-box" style="background-image:url(http://img.youtube.com/vi/' + yt_id + '/0.jpg);"><span class="youtube-title">' + yt_title + '</span><span class="youtube-bar"><span class="yt-bar-left"></span><span class="yt-bar-right"></span></span><span class="youtube-play"></span></div>');
$('div.youtube-box').click(function() {
$(this).replaceWith('<iframe class="youtube-frame" src="http://www.youtube.com/embed/' + yt_id + '?rel=0;&autoplay=1&vq=hd720"></iframe>');
// added to remove youtube playlist from iframe url
jQuery('iframe').attr('src',function(i,v){
return v.split('&l')[0]; // get the string part before the `?`
// or
// return v.replace(/\?.*/,'');
});
});
});
});
});
</script>
Answer to my second question, I put the code right before the code above to fix broken thumbnails:
<script>
$(window).on("load", function(){
jQuery('a').attr('href',function(i,v){
return v.split('&l')[0]; // get the string part before the `?`
// or
// return v.replace(/\?.*/,'');
});
});
</script>
I'm attempting to dynamically create an iFrame and add HTML into it from the current document. The iFrame gets created successfully, but when the function gets to the point where it needs to add the HTML in, it doesn't do it.
Here's my code:
function createiFrame(min, max, key) {
console.log("Max-Width", max);
//CREATING A CLASS FOR THE IFRAME
var iframeClass = key + "-" + max;
//var path = window.location.pathname;
//var page = path.split("/").pop();
//ADDING AN IFRAME INTO THE DOCUMENT AND ADDING ON THE CLASS
$(document).ready(function() {
$('<iframe>', {
width: max
}).addClass(iframeClass).prependTo('body');
});
var requiredHTML = document.getElementById('container').innerHTML;
console.log("RequiredHTML", requiredHTML);
//ADDING THE COLLECTED HTML INTO THE IFRAME -- THIS IS WHERE
//IT STOPS WORKING
$('.' + iframeClass).ready(function() {
console.log("iFrame ready");
$('.' + iframeClass).contents().find('body').html("<p>Testing it out</p>");
});
var $head = document.getElementsByTagName('head')[0].innerHTML;
$(document).ready(function() {
$('.' + iframeClass).contents().find('head').append($head);
});
}
EDIT
I've realised this problem is occurring because when I try to run that code, the DOM isn't ready yet.
So new question;
How do I get the DOM ready?
check out this post:
addEventListener to iFrame
you need to use
$('#myIFrame').load(function(){
....
$('.' + iframeClass).ready(function() {
...
}
Doesn't work because an iframe being ready doesn't trigger the Event 'DOMContentLoaded' which .ready() is waiting for. You'll need to refer directly to a document, which will then trigger the DOMContentLoaded event. This should work based on that.
$(iframeClass document).ready(function() {
...
}
I will stress though that this isn't something that I've tried before, but it seems like it's just a matter of which document you're referring to.
I'am trying to pass a variable/ value from the fancybox iframe to the parent window without success.
Fancybox is launched from a link with
class="fancybox fancybox.iframe"
My code in the fancybox.iframe is:
$(document).ready(function(){
$('.insert_single').click(function(){
var test = $('.members_body').find('{row.U_USERNAME}');
setTimeout(function(){ parent.$.fancybox.close();},300);return true;
});
});
Where '{row.U_USERNAME}' is the username to find in the iframe.
Then, in the parent there's the following code:
$(document).ready(function(){
$('.fancybox').fancybox(
{
openEffect:'fade',
openSpeed:500,
afterClose: function(){
alert($(".fancybox-iframe").contents().find(test));
$('#form input[name=username]').val()(test);return false;
}
}
);
});
But when the fancybox is closed, there's no alert showing up with the variable "test", nor the variable is showing up as a value or as a text in the input field of the form.
I've read and tried various solutions found here on stackoverflow without success.
Thanks in advance for helping
EDIT
Here's an Example
When the fancybox is closed the iframe is removed from the document. So you must use beforeClose event instead of afterClose
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500,
beforeClose: function() {
// working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
},
afterClose: function() {
// not working
var $iframe = $('.fancybox-iframe');
alert($('input', $iframe.contents()).val());
}
});
});
JSFiddle: http://jsfiddle.net/NXY7Y/1/
EDIT:
I edited your jsfiddle (http://jsfiddle.net/NXY7Y/9/). Update is in this link
http://jsfiddle.net/NXY7Y/13/
Main page javscript:
$(document).ready(function() {
$('a.fancybox').fancybox({
openEffect:'fade',
openSpeed:500//,
//beforeClose: function() {
// // working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//},
//afterClose: function() {
// // not working
// var $iframe = $('.fancybox-iframe');
// alert($('input', $iframe.contents()).val());
//}
});
});
function setSelectedUser(userText) {
$('#username').val(userText);
}
No need to use afterClose or beforeClose events. Just access the parent function setSelectedUser from the iframe on link click event like this:
$(document).ready(function() {
$('a.insert_single').click(function() {
parent.setSelectedUser($(this).text());
parent.$.fancybox.close();
});
});
Some clarifications :
You should use .find() to find elements by selector (you are trying to find a variable .find(test), which is not a valid format).
You should use .val() to get the contents of an input field or .val(new_value) to set the contents of an input field
You should use .html() or .text() to get the contents of any element other than input,
example: having this html code
<p class="test">hola</p>
... and this jQuery code
var temp = $(".test").html();
... temp will return hola.
On the other hand, if you have control over the iframed page and it's under the same domain than the parent page, then you may not need to set any jQuery in the child page.
so, having this html in the child (iframed) page for instance
<div class="members_body">
<p>GOOGLE</p>
<p>JSFIDDLE</p>
<p>STACKOVERFLOW</p>
</div>
You could set this jQuery in your parent page to get the contents of any clicked element in your child page :
var _tmpvar; // the var to use through the callbacks
jQuery(document).ready(function ($) {
$(".fancybox").fancybox({
type: "iframe",
afterShow: function () {
var $iframe = $('.fancybox-iframe');
$iframe.contents().find(".members_body p").each(function (i) {
$(this).on("click", function () {
_tmpvar = $('.members_body p:eq(' + i + ')', $iframe.contents()).html();
$.fancybox.close();
}); // on click
}); // each
},
afterClose: function () {
$('#form input[name=username]').val(_tmpvar);
}
});
}); // ready
Notice that we declared the var _tmpvar globally so we can use it within different callbacks.
See JSFIDDLE
I have simple content loader, where I load content of html file into element. That is working fine. But when I load content, then JS in content is not loaded because it is defined in main (index.html) document ready function.
Question:
How to load content where after page refresh it will remain in div?
Note: Prefer JS solution.
HTML:
index.html
<ul id="debug_menu">
<li>content1</li>
<li>content2</li>
<li>content3</li>
</ul>
<div id="zone"></div>
JS:
/* Content loader */
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery('#zone').load('content/' + $content + '.html');
});
});
//Edit:
jQuery(".dial").knob();
content1.html:
<input value="90" class="dial">
Note: using http://anthonyterrien.com/knob/ plugin
try something like this
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery('#zone').load('content/' + $content + '.html', function() {
jQuery(".dial").knob();//initialize new one
});
});
});
jQuery(".dial").knob();
EDITED CODE
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery('#zone').load('content/' + $content + '.html', function() {
initial_loader();//initialize new one
});
});
initial_loader();
});
function initial_loader(){
jQuery(".dial").knob();
}
When you load content, you should also manipulate the current page URL in a way that does not cause a reload. This basically means changing the hash part (#something). On page load, you only have to check the current hash and load the right content.
You can also use the history API with the same logic, it gives you more options to manipulate any part of the URL without a reload. Browser support is not the best yet though, but you can use history.js as a wrapper.
Advantages: both methods will make your content linkable and make the browser history usable (back, forward buttons will work) other than fixing your reload problem.
Not possible. You have to store which div is loaded etc.
Solutions where you can store something:
Cookie
Localstorage
Hashtag
I use this plugin: https://github.com/AlexChittock/JQuery-Session-Plugin
to store content variable into session.
/* Content loader */
jQuery(document).ready(function() {
jQuery("#debug_menu li").click(function() {
$content = jQuery(this).text();
jQuery.session.set('content', $content);
jQuery('#zone').load('content/' + $content + '.html',
function() {
initial_loader();
}
);
});
$s = jQuery.session.get('content');
jQuery('#zone').load('content/' + $s + '.html',
function() {
initial_loader();
}
);
});
function initial_loader() {
jQuery(".dial").knob();
}
I have a script that will reload the page (content) to a random DIV
How do I implement this so that the script loads after the div is loaded?
I have the following code ready:
<script>
$(document).ready(function() {
$("#getAssignment").click(function() {
var $divs = $(".assignment");
if ($divs.length > 0) {
window.location.hash = "#" + $divs[ Math.floor(Math.random() *
$divs.length) ].id;
}
});
});
</script>
$("div").load(function(){
blah();
});
This will do what you wanted, but it does not make sense though, since div is not like an image or <script> or a page. (You can't really "load" a <div> anyway.)