Does anyone know if there is such a thing?
I have a iframe that's being inserted with $.ajax() and I want to do some stuff after the contents from the iframe are completely loaded:
....
success: function(html){ // <-- html is the IFRAME (#theiframe)
$(this).html(html); // $(this) is the container element
$(this).show();
$('#theiframe').load(function(){
alert('loaded!');
}
....
it works, but I see the IFRAME is loaded twice (the alert also shows twice).
use iframe onload event
$('#theiframe').on("load", function() {
alert(1);
});
If possible, you'd be better off handling the load event within the iframe's document and calling out to a function in the containing document. This has the advantage of working in all browsers and only running once.
In the main document:
function iframeLoaded() {
alert("Iframe loaded!");
}
In the iframe document:
window.onload = function() {
parent.iframeLoaded();
}
Along the lines of Tim Down's answer but leveraging jQuery (mentioned by the OP) and loosely coupling the containing page and the iframe, you could do the following:
In the iframe:
<script>
$(function() {
var w = window;
if (w.frameElement != null
&& w.frameElement.nodeName === "IFRAME"
&& w.parent.jQuery) {
w.parent.jQuery(w.parent.document).trigger('iframeready');
}
});
</script>
In the containing page:
<script>
function myHandler() {
alert('iframe (almost) loaded');
}
$(document).on('iframeready', myHandler);
</script>
The iframe fires an event on the (potentially existing) parent window's document - please beware that the parent document needs a jQuery instance of itself for this to work. Then, in the parent window you attach a handler to react to that event.
This solution has the advantage of not breaking when the containing page does not contain the expected load handler. More generally speaking, it shouldn't be the concern of the iframe to know its surrounding environment.
Please note, that we're leveraging the DOM ready event to fire the event - which should be suitable for most use cases. If it's not, simply attach the event trigger line to the window's load event like so:
$(window).on('load', function() { ... });
That's the same behavior I've seen: iframe's load() will fire first on an empty iframe, then the second time when your page is loaded.
Edit: Hmm, interesting. You could increment a counter in your event handler, and a) ignore the first load event, or b) ignore any duplicate load event.
Without code in iframe + animate:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function resizeIframe(obj) {
jQuery(document).ready(function($) {
$(obj).animate({height: obj.contentWindow.document.body.scrollHeight + 'px'}, 500)
});
}
</script>
<iframe width="100%" src="iframe.html" height="0" frameborder="0" scrolling="no" onload="resizeIframe(this)" >
You may use the jquery's Contents method to get the content of the iframe.
If you want it to be more generic and independent, you can use cookie. Iframe content can set a cookie. With jquery.cookie and a timer (or in this case javascript timer), you can check if the cookie is set each second or so.
//token should be a unique random value which is also sent to ifame to get set
iframeLoadCheckTimer = window.setInterval(function () {
cookieValue = $.cookie('iframeToken');
if (cookieValue == token)
{
window.clearInterval(iframeLoadCheckTimer );
$.cookie('iframeToken', null, {
expires: 1,
path: '/'
});
}
}, 1000);
Related
My version that does not work:
$(window).on('load', function() {
var $iframe = $("<iframe>",
{id:"up2europe",
marginheight:"5",
marginwidth:"5",
src:"https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
});
$(".sidebar__right:first").append($iframe).on('load', function()
alert(document.getElementbyId("#up2europe").documentElement.title);
});
});
So... I'm trying to access the title of the iframe...to check if it was loaded properly.
There are more a couple of things wrong with your code:
You use $("...").append($iframe) which returns $("...") after the iframe is appended. That means that your load event is attached to $("...") rather than the iframe which is the logical thing to do in this case. To achieve that use $iframe.appendTo("..."), so that the return value of the method is $iframe.
You use getElementbyId inside the aforementioned load event listener which is basically the wrong way to write getElementById.
The argument you pass to alert inside the event listener isn't an effective way to get the title of the document of the iframe.
So, by correcting the above errors the code becomes:
$(window).on('load', function() {
/* Create the iframe. */
var $iframe = $("<iframe>", {
id: "up2europe",
marginheight: "5",
marginwidth: "5",
src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
});
/* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
$iframe.appendTo(".sidebar__right:first").on('load', function() {
/* 'this' refers to the iframe. */
alert(this.contentDocument.title);
});
Note: In order to actually get the title of the document of the iframe both the content of the iframe and the parent window must be served by the same domain, otherwise your code will fail due to the Same-Origin Policy.
Snippet:
(Getting the document title fails due to the same-origin policy; read the error thrown.)
$(window).on('load', function() {
/* Create the iframe. */
var $iframe = $("<iframe>", {
id: "up2europe",
marginheight: "5",
marginwidth: "5",
src: "https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d"
});
/* Using 'appendTo' ensures we add the 'load' event listener to the iframe. */
$iframe.appendTo(".sidebar__right:first").on('load', function() {
/* 'this' refers to the iframe. */
alert(this.contentDocument.title);
});
});
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class = "sidebar__right"></div>
Resource: You can read more about the Same-Origin Policy here.
If you only want to check whether the content of an iframe has loaded, you don't need to check its document's title, but rather simply attach a load event`:
$iframe.on("load", function () {
// code to execute after it's loaded.
});
I believe this is the right method to add an element with jQuery. Check out from this LINK.
Code:
$(window).on('load', function() {
var iframe = document.createElement('iframe');
$(iframe).css({'marginheight':'5px','marginwidth':'5px'});
$(iframe).attr({'src':'https://www.up2europe.eu/widget/go/181d4bdc08289da3d78b79ee5f9e7e2d','id':'up2europe','title':'Im iframe'});
$(".sidebar__right").append(iframe);
$(iframe).ready(function(){
alert($(iframe).attr('title'));
});
});
I am a newbie on javascript and was implementing a loader in the project..
I have used the below code for the implementation of loader but it is not working:-
var url = "http://localhost:3500/#!/Movies";
<script>
$(function(){ //Loader implementation
if (location.href==url){
$(window).ready(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
});
}
});
</script>
I am calling the loadindicator in the code as:-
<ul>
<li id="loadIndicator1" style="position:absolute ;top:50%;left:50%;z-index:99999;"></li>
</ul>
I am not very sure why this is giving an issue.I am using jquery-1.8.3.min.js and jqueryui-1.10.2.js
Also when I hover on location..I get unresolved variable location.Please help me with this.
use
if (window.location.href==url)
instead of
if (location.href==url)
var url = "http://localhost:3500/#!/Movies";
$(function(){
if (location.href==url){
$(window).load(function(){
$('#loadIndicator1').fadeIn(1000);
});
}
});
this will show your loader once the webpage is fully downloaded
use $('#loadIndicator1').fadeOut(1000); to hide the loader once the content is loaded.
Ignoring window ready, using only document ready
$(function() {
if (window.location.href === url){
// $(window).ready(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
// });
}
});
You should remove the part I have commented out. The problem is, you attached an event handler to document ready, and if your are on a specific URL, you attach an event handler to window ready, but that event was already fired, and it won't be fired again.
Using window load after document ready
Another possible solution:
$(function() {
if (window.location.href === url){
$(window).load(function(){
$('#loadIndicator1').fadeOut(1000);
return false;
});
}
});
The window load event fires later, than document ready - though this should be tested.
Ignoring document ready, using only window load
Third time is a charm, another solution which may be the best, simply ignore the document ready event, and only use the window load:
$(window).load(function () {
if (window.location.href === url) {
$('#loadIndicator1').fadeOut(1000);
return false;
}
});
This case though the loader only appears if everything is loaded on the page, so maybe this is not what you want -- in this case use the first option.
I am loading an embedded Google calendar the standard way:
<iframe id="calendar" src="https://www.google.com/calendar/embed...></iframe>
I want to apply some style changes after the load event using jQuery, e.g.:
$('iframe#calendar').contents().find('.blahblah').css("display", "none");
I presumably need to use an interval loop:
var interval_calendar = setInterval(function(){
if ($('#calendar').SOMETHING) {
clearInterval(interval_calendar);
$('iframe#calendar').contents().find('.blahblah').css("display", "none");
}
} ,200);
How can I check that the calendar is loaded? Basically, I need the SOMETHING.
Thanks.
Try
var iframe = $("<iframe>", {
"id" : "calendar",
"src" : "https://www.google.com/calendar/embed...",
"target" : "_top"
})
// `iframe` `load` `event`
.on("load", function (e) {
$(e.target)
.contents()
.find(".blablah")
.css("display", "none");
return false
});
// $(element).append($(iframe))
jsfiddle http://jsfiddle.net/guest271314/a3UL5/
You could use load to execute a function when your iframe is done loading...
$("#calendar").load( function () {
// do something once the iframe is loaded
});
I can not find any good JavaScript Event solution, but you can use your idea:
var interval_calendar = setInterval(function(){
if ($('#calendarTitle').html()!= "") {
clearInterval(interval_calendar);
alert();
}
} ,200);
The calendarTitle id is shown on the page only when the whole calendar loaded.
In the other hand I don't know if you can access the calendar attributes, as they are protected. You can only access the iframe content that was loaded from your host. With an alert()
it works, but if you try to access any inside content you will get a SecurityError message into console.
i have a script that cuts a part of the iframe( iframe without headers ) and shows it. my problem is if i make actions within this iframe, the iframe reloads but is not applying the jquery filtering to give me only that part but instad gives me all the page with headers so i'm assuming that script is not working when it reload the iframe without the window reload of the main page that has the iframe:
<iframe class="test" width="100%" height="100%" src="/message.html?msjId=260" style="height:100%;width:100%;">
$(window).load(function () {
$('.test').each(function(){
var filteredContents1 = $(this).contents().find('.div_iframe').html();
$(this).contents().find('body').html(filteredContents1);
});
});
any solutions please ?
I think you need to add load events for frames as well. Add the load event in document.ready function as given below. If it works you may be able to omit window load event you already have for filtering frames data.
$(document).ready(function(){
$('.test').load(function () {
var filteredContents1 = $('#frame1').contents().find('#divChild').html();
$('#frame1').contents().find('body').html(filteredContents1);
});
});
Update on request of questioner
$(document).ready(function(){
$('.test').load(function () {
$('#frame1, #frame2, #frame3').each(function(){
var filteredContents1 = $(this).contents().find('#divChild').html();
$(this).contents().find('body').html(filteredContents1);
});
});
});
.
After the request, the new elements created are not recognized by the event handlers in my jQuery code.
Is there a way to reload the file to re-register these events?
I'm assuming that you mean that events you've registered for elements that have been replaced by with the results of your ajax requests aren't firing?
Use .live() (see http://api.jquery.com/live/) to register the events against elements that the match the selector (including the new DOM elements created from the results of the ajax), rather than the results of the selector when the event handlers were first, which will be destroyed when they are replaced.
e.g.
replace
$('div.someClass').click(function(e){
//do stuff
});
with
$('div.someClass').live('click', function(e){
//do stuff
});
Important:
While I've recommended using .live() this is for clarity as its syntax is similar to .bind(), you should use .on() if possible. See links in #jbabey's comment for important information.
This question was about binding event handler on DOM element created after the loading of the page. For instance, if after a request ajax you create a new <div> bloc and want to catch the onClick event.
//This will work for element that are present at the page loading
$('div.someClass').click(function(e){
//do stuff
});
// This will work for dynamically created element but is deprecated since jquery 1.7
$('div.someClass').live('click', function(e){
//do stuff
});
// This will work for dynamically created element
$('body').on('click', 'div.someClass', function(e){
//do stuff
});
You would find the documentation here: http://api.jquery.com/on/
This codes works perfect for me..
$("head script").each(function(){
var oldScript = this.getAttribute("src");
$(this).remove();
var newScript;
newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = oldScript;
document.getElementsByTagName("head")[0].appendChild(newScript);
});
It removes the old script tag and make a new one with the same src (reloading it).
To increase the website performance and reduce the total file’s size return, you may consider to load JavaSript (.js) file when it’s required. In jQuery, you can use the $.getScript function to load a JavaScript file at runtime or on demand.
For example,
$("#load").click(function(){
$.getScript('helloworld.js', function() {
$("#content").html('Javascript is loaded successful!');
});
});
when a button with an Id of “load” is clicked, it will load the “helloworld.js” JavaScript file dynamically.
Try it yourself
In this example, when you clicked on the load button, it will load the “js-example/helloworld.js” at runtime, which contains a “sayhello()” function.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
</head>
<body>
<h1>Load Javascript dynamically with jQuery</h1>
<div id="content"></div>
<br/>
<button id="load">Load JavaScript</button>
<button id="sayHello">Say Hello</button>
<script type="text/javascript">
$("#load").click(function(){
$.getScript('js-example/helloworld.js', function() {
$("#content").html('
Javascript is loaded successful! sayHello() function is loaded!
');
});
});
$("#sayHello").click(function(){
sayHello();
});
</script>
</body>
</html>
In your request callback, call a function that acts on your newly appended or created blocks.
$.ajax({
success: function(data) {
$('body').append(data);
//do your javascript here to act on new blocks
}
});
simple way to solve this problem
$(document).ready(function(){
$('body').on('click','.someClass',function(){
//do your javascript here..
});
});
You can also attach the click handlers to the body so that they never get destroyed in the first place.
$('body').on('click', 'a', function(event) {
event.preventDefault();
event.stopPropagation();
// some stuff
})
var scripts = document.getElementsByTagName("script");
for (var i=0;i<scripts.length;i++) {
if (scripts[i].src)
if(scripts[i].src.indexOf('nameofyourfile') > -1 )
var yourfile = scripts[i].src;
}
jQuery.get(yourfile, function(data){
if(data){
try {
eval(data);
} catch (e) {
alert(e.message);
}
}
});
You can try loadscript plugin for loading the javascript file.
forexample
$("#load").click(function(){
$.loadScript('path/example.js');
});
or
$.ajax({
success: function(data) {
$.loadScript('path/example.js');
}
});
http://marcbuils.github.io/jquery.loadscript/
What do you mean not recognized by jQuery?
jQuery walks the DOM each time you make a request, so they should be visible. Attached events however will NOT be.
What isn't visible exactly?
P.S.: Reloading JavaScript is possible, but highly discouraged!