Loading JavaScript when div has loaded? - javascript

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.)

Related

Check if all/multiple iframes are loaded

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>');
});
});
}
});
});
});

Execute a function after a redirection jQuery / JavaScript

I would like to execute a function after a redirection on my site. Here is my code:
$('a.filter-redirect').on('click', function(){
window.location.replace('/technos/');
filter();
});
And here is my function "filter":
$('a.filter-tech').on('click', function filter(){
var tag = $(this).attr('rel');
var val_input = $('#tag').val();
if(tag === val_input){
$('#tag').val('');
$('#form').submit();
}
if(val_input){
$('#tag').val(val_input + ',' + tag)
}
$('#tag').val(tag);
$('#form').submit();
return false;
});
I am not an expert in JS and jQuery and the code may be wrong. My function works, but not after the redirection.
when you redirect to a new page the scripts on the previous page are no more executed. So you have to call this function as soon as the new page is loaded e.g. on $(window).load() or $(document).ready() not on an click in previous page.
$(document).ready(function(){
var tag = $(this).attr('rel');
var val_input = $('#tag').val();
if(tag === val_input){
$('#tag').val('');
$('#form').submit();
}
if(val_input){
$('#tag').val(val_input + ',' + tag)
}
$('#tag').val(tag);
$('#form').submit();
return false;
})
When you redirect your page location changes, which means that a new page is loaded and the old is gone.
To do some action in the new page you have to add it in that page (for example in the body on load or in a script tag)
When you go to the new page, keep all your required code inside $(document).ready() or window.load()
Somthing like this
function runOnPageLoad() {
alert('Hey There');
}
window.onload = runOnPageLoad;
Or in jquery as
$(document).ready ( function(){
alert('Hey There');
});​
Hope it helps

Reload Div content on interval with jQuery

I am trying to modify a page so that I can reload the content of a div on an interval. This is what I tried:
$("#thediv").load("/thecontent.php");
setTimeout(doPoll,1000);
}
However, using Fiddler reveals that the requests are never made.
Try with this one:
$(document).ready(function() {
setInterval(function() {
$("#thediv").load("thecontent.php");
}, 3000);
});
var content = ''; // file
var element = ''; // id or class
$(window).load(function(){
window.setTimeout("doPoll()",1000);
});
function doPoll(){
(element).load(content);
}

JavaScript code in iframe doesn't work

I have an iframe which is created after loading page. (main DOM)
var object_preview = $('#preview');
var iframe = $('<iframe id="preview_frame">'),
iframe_body,
iframe_head;
object_preview.html(iframe);
setTimeout(function() {
var doc = iframe[0].contentWindow.document;
iframe_body = $('body', doc);
iframe_head = $('head', doc);
}, 1);
When you click on a button, in the iframe head inserted JS-code (jQuery), which must be executed within the iframe DOM.
$('#run').click(function() {
iframe_body.append('<script type="text/javascript">\
$(document).ready(function() {\
$(".test").click(function() { alert(true); });\
});\
</script>');
});
Now it doesn't work. How to implement it?
Element with class .test is within iframe DOM.
HTML structure:
Thanks in advance.

document ready after dom manipulation

I'm doing an application with Phonegap and I'm using a self-built slide transition to change the pages.
It works like this:
Every page is a div with 100% height and width, so if I change the Page, I set the next div right to the currently active and slide both to the left side.
Now to the Problem: the sliding works fine, but it's executed before the content of the right div is completely loaded. So the right div slides in empty, and only after a few hundred miliseconds the content will appear.
I tried it with document.ready, but as I've read this event is only executed the first time the DOM is loaded.
Does anybody know how I can wait for the DOM to be completely rendered again after I've manipulated the DOM with Javascript?
In your case, you can pick one element in the content of the next div and keep checking it with $(...).length. If the value is > 0, the DOM is loaded and you can change the page.
You may want to try this function:
Function.prototype.deferUntil = function(condition, timeLimit) {
var ret = condition();
if (ret) {
this(ret);
return null;
}
var self = this, interval = null, time = ( + new Date());
interval = setInterval(function() {
ret = condition();
if (!ret) {
if (timeLimit && (new Date() - time) >= timeLimit) {
// Nothing
} else {
return;
}
}
interval && clearInterval(interval);
self(ret);
}, 20);
return interval;
};
Usage:
(function() {
console.log('Next page loaded');
}).deferUntil(function() {
return $('#nextDiv').length > 0;
}, 3000);
The above example will check the div that has id="nextDiv" in every 20ms (not longer than 3 seconds). When the div is loaded, it will show 'Next page loaded' in the console.
You can try on this fiddle
There is a DOMNodeInserted event that is supposed to work like document.ready but for individual DOM nodes. But it is deprecated and has lots of issues. StackOverflow users found a good alternative to it that works quite well in all mobile browsers: Alternative to DOMNodeInserted
Here is a function that will trigger a callback once all images matching a jquery selector have finished loading
Js Fiddle Sample
//css
input {width: 420px;}
//html
<div id="container"></div>
<input type="text" value="http://goo.gl/31Vs" id="img1">
<br><input type="text" value="http://wall.alafoto.com/wp-content/uploads/2010/11/Fractal-Art-Wallpapers-09.jpg" id="img2">
<br><input type="text" value="http://pepinemom.p.e.pic.centerblog.net/ssg8hv4s.jpg" id="img3">
<br><input type="button" value="Load images" name="loadImages" id="btn">
<div id="message"></div>
//javascript
//Call a function after matching images have finished loading
function imagesLoadedEvent(selector, callback) {
var This = this;
this.images = $(selector);
this.nrImagesToLoad = this.images.length;
this.nrImagesLoaded = 0;
//check if images have already been cached and loaded
$.each(this.images, function (key, img) {
if (img.complete) {
This.nrImagesLoaded++;
}
if (This.nrImagesToLoad == This.nrImagesLoaded) {
callback(This.images);
}
});
this.images.load(function (evt) {
This.nrImagesLoaded++;
if (This.nrImagesToLoad == This.nrImagesLoaded) {
callback(This.images);
}
});
}
$("#btn").click(function () {
var c = $("#container"), evt;
c.empty();
c.append("<img src='" + $("#img1").val() + "' width=94>");
c.append("<img src='" + $("#img2").val() + "' width=94>");
c.append("<img src='" + $("#img3").val() + "' width=94>");
evt = new imagesLoadedEvent("img", allImagesLoaded);
});
function allImagesLoaded(imgs) {
//this is called when all images are loaded
$("#message").text("All images loaded");
setTimeout(function() {$("#message").text("");}, 2000);
}
You could use jQuery ajax to load the content, and on success run a function with the slide.
$("#page1").load('page2.html', function() {
//do your custom animation here
});
Althoug I'm not completely sure how you're loading the content. Is it static (Already there but just not visible?) Or is it loaded with ajax?
EDIT: You could just do a small .delay() or setTimeout with a few millisec, and then animate the sliding.
I had a similar problem making a masonry site responsive. I use window.onload which waits for all elements to complete loading before initialising masonry.js. I also placed the window.onload inside .onchange function and it fired everytime the viewport resized.
I am sure applying similar principles will solve your problem.
try once
$(window).bind('load',function(){
//code
});
Maybe you can set an event on your div.
myDiv.onafterupdate = myHandler;
function myHandler() {
// Do here what you want to do with the updated Div.
}
Does this help you?
In jquery you could use $() just after your DOM manipulation code.
$(function(){
//code that needs to be executed when DOM is ready, after manipulation
});
$() calls a function that either registers a DOM-ready callback (if a function is passed to it) or returns elements from the DOM (if a selector string or element is passed to it)
You can find more here
difference between $ and $() in jQuery
http://api.jquery.com/ready/

Categories

Resources