How can I make this function execute automatically / on load [duplicate] - javascript

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.

If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.

Another way to do this is by using event listeners, here's how you use them:
document.addEventListener("DOMContentLoaded", function() {
your_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.

Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply
The typical options is using the onload event:
<body onload="javascript:SomeFunction()">
....
You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
Another option is to use a JS framework which intrinsically does this:
// jQuery
$(document).ready( function () {
SomeFunction();
});

function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
Using Multiple JavaScript Onload Functions

<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>

You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>

here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}

For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

Related

multiple $(document).ready and $(window).load in $(document).ready

I got 2 questions. First of all, this is not my work. I'm currently looking at somebody else's JavaScript files. I can't give the exact code but I can show what I'm wondering.
In the JavaScript files I see a lot of $(document).ready(function(){});. I know what $(document).ready does, the callback function will be called when the DOM tree is loaded. Is there any reason why somebody would use more than one $(document).ready callback? I don't get the point.
Also, another thing I saw was a $(window).load inside a $(document).ready, like this:
$(document).ready(function() {
$(window).load(function() {
//...
});
});
From what I know, $(window).load() is called when everything of a page is loaded, like assets and images etc. I would think $(window).load() is the last thing called, after $(document).ready. Is there any time where $(window).load is called BEFORE $(document).ready and is there any reason why you would put a $(window).load inside a $(document).ready?
Yes, jQuery grants that ready event will be called before load. Even in IE8- (where DOMContentLoaded is not supported) it works in that way. But let's look at the following code:
<!doctype html>
<title>Ready vs load test</title>
<style>body {white-space: pre}</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
~function () {
function log(msg) {
document.body.innerHTML += msg + "\n";
}
function handler(msg) {
return function () {
log(msg);
}
}
$(window).load(handler("5. load #1"));
$(document).ready(handler("1. ready #2"));
$(window).load(handler("6. load #3"));
$(document).ready(handler("2. ready #4"));
$(document).ready(function () {
log("3. ready #5");
$(window).load(handler("8. load #6"));
});
$(document).ready(handler("4. ready #7"));
$(window).load(handler("7. load #8"));
}();
</script>
The result is
1. ready #2
2. ready #4
3. ready #5
4. ready #7
5. load #1
6. load #3
7. load #8
8. load #6
Look at lines 7 and 8. The load handled attached from ready event is the last one. So by using this way we can ensure that all previously added (during scripts parsing and exection) load handlers have already been called.
so using $(window).load outside the $(document).ready and inside doesn't change that much from how it'd affect how stuff work?
Actually it can affect script execution. The first version works and the second doesn't:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$(window).load(function () {
$.magic.value = 12;
});
});
</script>
<script>
$(window).load(function () {
$.magic = {};
});
</script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
});
$(window).load(function () {
$.magic.value = 12;
});
</script>
<script>
$(window).load(function () {
$.magic = {};
});
</script>
$(document).ready kicks in when all nodes of the DOM have been loaded but not necessarily their content, that's what's $(window).load is for, e.g. an img-ele can be present, yet it's content – the image – hasn't been loaded.
So, you're right, use each listener only once and don't nest them.

window.onload in external script gets ignored in Javascript

index.html
<html>
<head>
<script type="text/javascript" src="foo.js"></script>
<script type="text/javascript">
window.onload = function() {
console.log("hello from html");
};
</script>
</head>
<body>
<div class="bar">bar</div>
</body>
</html>
foo.js
// this js file will be completely ignored with window.onload
//window.onload = function() {
console.log("hello from external js");
var bar = document.getElementsByClassName("bar");
// this returns 0 instead of 1
console.log(bar.length);
//};
When window.onload is used in html, window.onload from external js will be ignored.
When window.onload from external js is commented out, bar.length returns 0.
When window.onload from html is removed, window.onload from external js works fine.
Can anyone explain why I can't use both window.onload?
If I had to use window.onload in html, how do tell if window is loaded from external js?
1)The way you're binding, you can have just one method attached to an event. You need to add an event listener for what you want.
window.addEventListener("load", function() { alert("hello!");});
Setting directly a method to the onload event will replace any previously attached method. But if you use listeners instead, you can have many of them bound to an event.
2)If you comment out the onload in your external file, when the document.getElementsByClassName("bar") is called, your document isn't ready yet, then, it will return 0 items.
3)Use the addEventListener as I explained in the first point. If you apply this in both places, it will work like a charm.
onload is a property of window. It acts like any other variable property. When you try to use it twice you're overwriting the original value with your second write.
So your entire external script is ignored when you wrap it in window.onload, because window.onload is then overwritten to be
function() {
console.log("hello from html");
};
If you want to do execute 2 functions, define 2 functions, a and b,
and set window.onload like this:
window.onload = function(){
a();
b();
}
Alternatively, you can bind 2 separate events in the way Alcides' answer suggests. My personal view is that its cleaner to do a single bind with multiple functions since its easier to know whats bound, know what order your functions will execute in, and see everything thats happening in one place, but its mostly a matter of style/preference if the order doesn't matter.
Thats Correct, you are overwriting your own onload, but you can always attach a new event listener to the window like this
function onLoadHandler(){
console.log("hello from external js");
var bar = document.getElementsByClassName("bar");
// page not loaded, so this returns 0 instead of 1
console.log(bar.length);
}
if (window.addEventListener) {
window.addEventListener('load', onLoadHandler); }
else if (window.attachEvent) { window.attachEvent('onload', onLoadHandler ); }

Execute javascript after a partial postback of an updatepanel?

I have a page that add tree file script to it .
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/init.js"></script>
<script type="text/javascript" src="js/easing.js"></script>
I have a updatepanel with a dropdownlist. When run SelectedIndexChanged event (partial postback of an updatepanel), don't execute javascript .
Use the pageLoad function:
function pageLoad(sender, args) {
InitialiseSettings();
}
function InitialiseSettings(){
// replace your DOM Loaded settings here.
// If you already have document.ready event,
// just take the function part and replace here.
// Not with document.ready
$(element).slideUp(1000, method, callback});
$(element).slideUp({
duration: 1000,
easing: method,
complete: callback});
}
Or, try adding an "end request" event handler with .add_endRequest():
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(InitialiseSettings)
Edit:
It would be a better idea for you to move your code from document.ready into InitialiseSettings(), and to then register it as a pageLoaded event handler.
Code Example
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(InitialiseSettings)
To run your javascript in full and partial postbacks, put your javascript code into javascript pageLoad() function.
function pageLoad()
{
//your javascript code
}
Example:
function pageLoad() {
$(':submit').click(function () {
CommodityArray();
});
$('#btn_image').click(function () {
CommodityArray();
});
$(".repHeader").disableSelection();
CommodityArray();
}
Hope it helps! :)
You have to use following code after your update panel.
<script type="text/javascript" language="javascript">
var pageRequestManager = Sys.WebForms.PageRequestManager.getInstance();
pageRequestManager.add_endRequest(NewCharacterCount);
</script>
where NewCharacterCount is your javascript function name.
Read this article Sys.WebForms.PageRequestManager endRequest Event
Hope it may help you.
If you are using UpdatePanel and you want to call a javascript function after content refresh in update panel, you can use below way to do it easily. In Page body tag , call a function RefreshContent()
<body onload="RefreshContent()">
<script type="text/javascript">
function RefreshContent()
{
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler);
}
function EndRequestHandler()
{
alert("Add your logic here" );
}
</script>
Reference link
http://www.infoa2z.com/asp.net/how-to-call-javascript-function-after-an-updatepanel-asychronous-request-to-asp.net-page
You can use PageRequestManager client events. The sender parameter will contain the information you need. For example one could do this:
// Register event handler
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);
/// Executed when all page content is refreshed, full page or async postback: https://msdn.microsoft.com/en-us/library/bb397523.aspx
function pageLoaded(sender, args) {
var isPostBack = sender.get_isInAsyncPostBack();
if(!isPostBack) return;
// PostBack logic here.
}

Detect click event inside iframe

I'm writing a plugin for TinyMCE and have a problem with detecting click events inside an iframe.
From my search I've come up with this:
Loading iframe:
<iframe src='resource/file.php?mode=tinymce' id='filecontainer'></iframe>
HTML inside iframe:
<input type=button id=choose_pics value='Choose'>
jQuery:
//Detect click
$("#filecontainer").contents().find("#choose_pic").click(function(){
//do something
});
Other posts I've seen usually have a problem with different domains (this hasn't). But, still, the event isn't detected.
Can something like this be done?
I solved it by doing like this:
$('#filecontainer').load(function(){
var iframe = $('#filecontainer').contents();
iframe.find("#choose_pics").click(function(){
alert("test");
});
});
I'm not sure, but you may be able to just use
$("#filecontainer #choose_pic").click(function() {
// do something here
});
Either that or you could just add a <script> tag into the iframe (if you have access to the code inside), and then use window.parent.DoSomething() in the frame, with the code
function DoSomething() {
// do something here
}
in the parent.
If none of those work, try window.postMessage. Here is some info on that.
$("#iframe-id").load( function() {
$("#iframe-id").contents().on("click", ".child-node", function() {
//do something
});
});
I know this is old but the ID's don't match in your code one is choose_pic and one is choose_pics:
<input type=button id=choose_pics value='Choose'>
$("#filecontainer").contents().find("#choose_pic").click(function(){
//do something
});
The tinymce API takes care of many events in the editors iframe. I strongly suggest to use them. Here is an example for the click handler
// Adds an observer to the onclick event using tinyMCE.init
tinyMCE.init({
...
setup : function(ed) {
ed.onClick.add(function(ed, e) {
console.debug('Iframe clicked:' + e.target);
});
}
});
Just posting in case it helps someone. For me, the following code worked perfect:
$(document).ready(function(){
$("#payment_status_div").hide();
var iframe = $('#FileFrame').contents();
iframe.find("#take_payment").click(function(){
$("#payment_status_div").show("slow");
});
});
Where 'FileFrame' is the iframe id and 'take_payment' is the button inside iframe. Since my form inside the iframe is posted to a different domain, when used load, I got an error message saying:
Blocked a frame with origin "https://www.example.com" from accessing a frame with origin "https://secure-test.worldpay.com". Protocols, domains, and ports must match.
In my case there were two jQuery's, for the inner and outer HTML. I had four steps before I could attach inner events:
wait for outer jQuery to be ready
wait for iframe to load
grab inner jQuery
wait for inner jQuery to be ready
$(function() { // 1. wait for the outer jQuery to be ready, aka $(document).ready
$('iframe#filecontainer').on('load', function() { // 2. wait for the iframe to load
var $inner$ = $(this)[0].contentWindow.$; // 3. get hold of the inner jQuery
$inner$(function() { // 4. wait for the inner jQuery to be ready
$inner$.on('click', function () { // Now I can intercept inner events.
// do something
});
});
});
});
The trick is to use the inner jQuery to attach events. Notice how I'm getting the inner jQuery:
var $inner$ = $(this)[0].contentWindow.$;
I had to bust out of jQuery into the object model for it. The $('iframe').contents() approach in the other answers didn't work in my case because that stays with the outer jQuery. (And by the way returns contentDocument.)
If anyone is interested in a "quick reproducible" version of the accepted answer, see below. Credits to a friend who is not on SO. This answer can also be integrated in the accepted answer with an edit,...
(It has to run on a (local) server).
<html>
<head>
<title>SO</title>
<meta charset="utf-8"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<style type="text/css">
html,
body,
#filecontainer {
width: 100%;
height: 100%;
}
</style>
</head>
<body>
<iframe src="http://localhost/tmp/fileWithLink.html" id="filecontainer"></iframe>
<script type="text/javascript">
$('#filecontainer').load(function(){
var iframe = $('#filecontainer').contents();
iframe.find("a").click(function(){
var test = $(this);
alert(test.html());
});
});
</script>
</body>
</html>
fileWithLink.html
<html>
<body>
SOreadytohelp
</body>
</html>
In my case, I was trying to fire a custom event from the parent document, and receive it in the child iframe, so I had to do the following:
var event = new CustomEvent('marker-metrics', {
detail: // extra payload data here
});
var iframe = document.getElementsByTagName('iframe');
iframe[0].contentDocument.dispatchEvent(event)
and in the iframe document:
document.addEventListener('marker-metrics', (e) => {
console.log('#####', e.detail);
});
try
$('#yourIframeid').on("load", function () {
$(this).contents().on("contextmenu, keydown, mousedown, mouseup, click", function (e) {
//do your thing
});
});
use $('#yourIframeid').on("load") if $('#yourIframeid').onload( does not work.

How do I call a JavaScript function on page load?

Traditionally, to call a JavaScript function once the page has loaded, you'd add an onload attribute to the body containing a bit of JavaScript (usually only calling a function)
<body onload="foo()">
When the page has loaded, I want to run some JavaScript code to dynamically populate portions of the page with data from the server. I can't use the onload attribute since I'm using JSP fragments, which have no body element I can add an attribute to.
Is there any other way to call a JavaScript function on load? I'd rather not use jQuery as I'm not very familiar with it.
If you want the onload method to take parameters, you can do something similar to this:
window.onload = function() {
yourFunction(param1, param2);
};
This binds onload to an anonymous function, that when invoked, will run your desired function, with whatever parameters you give it. And, of course, you can run more than one function from inside the anonymous function.
Another way to do this is by using event listeners, here's how you use them:
document.addEventListener("DOMContentLoaded", function() {
your_function(...);
});
Explanation:
DOMContentLoaded It means when the DOM objects of the document are fully loaded and seen by JavaScript. Also this could have been "click", "focus"...
function() Anonymous function, will be invoked when the event occurs.
Your original question was unclear, assuming Kevin's edit/interpretation is correct, then this first option doesn't apply
The typical options is using the onload event:
<body onload="javascript:SomeFunction()">
....
You can also place your JavaScript at the very end of the body; it won't start executing until the doc is complete.
<body>
...
<script type="text/javascript">
SomeFunction();
</script>
</body>
Another option is to use a JS framework which intrinsically does this:
// jQuery
$(document).ready( function () {
SomeFunction();
});
function yourfunction() { /* do stuff on page load */ }
window.onload = yourfunction;
Or with jQuery if you want:
$(function(){
yourfunction();
});
If you want to call more than one function on page load, take a look at this article for more information:
Using Multiple JavaScript Onload Functions
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function codeAddress() {
alert('ok');
}
window.onload = codeAddress;
</script>
</head>
<body>
</body>
</html>
You have to call the function you want to be called on load (i.e., load of the document/page).
For example, the function you want to load when document or page load is called "yourFunction". This can be done by calling the function on load event of the document. Please see the code below for more detail.
Try the code below:
<script src="js/jquery-1.11.0.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
yourFunction();
});
function yourFunction(){
//some code
}
</script>
here's the trick (works everywhere):
r(function(){
alert('DOM Ready!');
});
function r(f){/in/.test(document.readyState)?setTimeout('r('+f+')',9):f()}
For detect loaded html (from server) inserted into DOM use MutationObserver or detect moment in your loadContent function when data are ready to use
let ignoreFirstChange = 0;
let observer = (new MutationObserver((m, ob)=>
{
if(ignoreFirstChange++ > 0) console.log('Element added on', new Date());
}
)).observe(content, {childList: true, subtree:true });
// TEST: simulate element loading
let tmp=1;
function loadContent(name) {
setTimeout(()=>{
console.log(`Element ${name} loaded`)
content.innerHTML += `<div>My name is ${name}</div>`;
},1500*tmp++)
};
loadContent('Senna');
loadContent('Anna');
loadContent('John');
<div id="content"><div>

Categories