window.onload function called twice - javascript

I have a simple form with post method. I am not sure why window.onload() function gets called twice below it shows up the page? Below is the code
function window.onload() {
initialisePage();
}
<form id="frmMain" method="post" runat="Server">
</form>
I tried using document.isready function before calling initialisePage didn't help.

If window.onload gets called twice, means some changes are still happening on front side after initial load.
A better to way would be by checking
window.onload = function() {
if(document.readyState == 'complete') {
myFunction();
}
};

SYNTAX ERROR in your code. onload should be written as follow:
<script>
window.onload = function() {
initialisePage();
}
</scipt>
OR
window.onload = initialisePage; // Thanks to #nnnnnn
Documentation

You can use below line of code :
$(document).ready(function(){
initialisePage();
})

<script>
window.onload = initialisePage;
</scipt>

Related

Javascript functions still remain after loading another partial

let's suppose the browser rendered following page
<html>
...
<body>
<div id="partialContainer">
<script>
function saveItems(){
/* do somthing*/
}
</script>
<input type="button" id="btnTest" name="btnTest" value="Test" onclick="saveItems()"/>
</div>
</body>
</html>
after an AJAX call and change the "partialContainer" content using
$("#partialContainer").html(returnedMarkup)
saveItems function still remains in page and can get executed
how can remove this function when markup get replaced to avoid name colissioning
var saveItems = function () {}
After your Ajax, assign some other value to it, preferably the one above.
Try setting saveItems to undefined
$("#partialContainer").html(returnedMarkup);
if (!!saveItems && $.isFunction(saveItems)) saveItems = void 0;
You could put your function in an object literal:
var obj = { saveItems: function() { } }
and delete it after the ajax
delete obj.saveItems
On your ajax success callback function, just do:
$("#btnTest").prop( "onclick", null );
Be aware that $.removeAttr('onclick') will fail in ie 6-8, so .prop() is better.

HTML onload not working

I'm attempting to use html onload event to trigger javascript, but is not working. The original code was:
html:
<div id='map' onload="generateMap.createMap();"></div>
JS:
var generateMap = function(){
return{
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
}
In an attempt to test, I changed the html to:
<div id='map' onload="alert('test');"></div>
Can anyone tell me why nothing is working?
First, the onload attribute is not valid for a div tag. You most likely intended to place the onload in the body tag.
Unfortunately, that's not the only problem.
In your onLoad you are referencing generateMap as if it is an object with method createMap. However, this is not the case. You have assigned generateMap to an anonymous function.
To get your code working, generateMap needs to be an object with method createMap.
You just need to set it as an object in the first place:
var generateMap = {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
};
Or if you need to retain the anonymous function for whatever reason, you can use an immediately executing function:
var generateMap = (function(){
return {
createMap: function(){
console.log(this.attr('id'));
element = this.attr('id');
navigator.geolocation.getCurrentPosition(initialize);
}
})();
There is no onload event for a div. You can use the script tag just after the div tag to emulate onload behavior.
Use this
<head>
<meta charset="utf-8">
<script type="text/javascript">
var generateMap = {
createMap: function(element) {
navigator.geolocation.getCurrentPosition(initialize);
}
};
</script>
</head>
<body>
<div id='map'></div>
<script type="text/javascript">
generateMap.createMap('map');
</script>
</body>
Assuming Chrome.. div tags do not have an onload event. Check the following two jsfiddles:
Does not work:
http://jsfiddle.net/o81e4dkr/
Works:
http://jsfiddle.net/p3osqrdn/
I do not know of a way to have an event fired when a div is loaded, unless it is being loaded in via jQuery.load(), in which case you can use the callbacks.
If you're using jQuery then I like the following function which adds onload capability to all tags:
$(document).ready (function () {
jQuery.each ($("[onload]"), function (index, item) {
$(item).prop ("onload").call (item);
return false;
});
});

Click a button element on page load

I'm trying to auto-click a button to initiate a function when the html page loads. I've tried document.getElementById('watchButton').click and it doesn't seem to work, the button is not clicked. Any suggestions?
<div class="content">
<div class="action-area ch30">
<button class="button dh" id="watchButton">Start Geolocation Watch</button>
<button class="button dh" id="refreshButton" >Refresh Geolocation</button>
</div>
The javascript:
run:function() {
var that = this;
document.getElementById("watchButton").addEventListener("click", function() {
that._handleWatch.apply(that, arguments);
}, false);
document.getElementById("refreshButton").addEventListener("click", function() {
that._handleRefresh.apply(that, arguments);
}, false);
},
Thanks!
I'd put it inside document.ready (so it doesn't fire until the DOM loads) and use jQuery syntax:
$(function() {
$('#watchButton').click();
});
http://jsfiddle.net/isherwood/kVJVe/
Here's the same fiddle using jQuery syntax: http://jsfiddle.net/isherwood/kVJVe/4
That said, why not just name your function and call it directly?
It would be click() not click
document.getElementById("watchButton").click();
You would need to call it onload or after the function has run
window.onload = function () {
document.getElementById("watchButton").click(); };
Try this ^^
try trigger
<script>
$(document).ready(function() {
$("#watchButton").trigger('click');
});
</script>
document.getElementById("studyOne").click();
$("#studyOne").trigger('click');
Put this in onload function. It worked for me.

Calling Javascript method defined above on page load

I am brand new to JavaScript so bear with me. I have a JavaScript function that is on my page:
<script type="text/javascript">
Sys.debug = true;
var popup;
Sys.require(Sys.components.popup, function () {
popup = Sys.create.popup("#popup", {
parentElementID: "target",
});
});
</script>
It works perfectly when I use it as an event:
<input type="button" onclick="popup.show()" value="Edit Theme" style="float: right; margin-right: 7.25em;" />
I want to call it on page load, inside the body tag I have the following code:
<script>
window.onload = popup.show;
</script>
The method does not appear to get called. What am I doing wrong?
Based on the documentation on Sys.Require, it seems that Sys.Require is called on load, which means that based on the ASP.Net page lifetime the script hasn't loaded when the onload event fires.
It looks like you can use Sys.onReady() instead:
Sys.onReady(function(){
popup.show();
})
You should write:
window.onload = popup.show;

Best way to modify an element that is not yet created

I have an <input> field in my web page, and I want to add a particular method on it, let say fooBar().
Here is what I do:
<input id="xxx" .../>
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
This works well. However, for some reasons I will not detail here (in fact the HTML is generated by JSF components), the <script> will be declared before the <input> tag.
So in others words, I will have that in my HTML:
<script type="text/javascript">
$("xxx").fooBar = function() { ... };
</script>
<input id="xxx" .../>
So of course this code will not work correctly, as the script will try to get ($("xxx")) and modify an element that does not exist yet.
If I want to stick on the exact order of these two tags, what is the best way to accomplish what I want?
Edit
In my case, $ refers to prototype, but I am also using jQuery in my application. And I must be compatible with IE6 :o(
You need to run your script after the document is loaded. With jQuery you'd do that with:
$(document).ready(function () {
//do stuff here
});
I can't tell which library you're using here, but they all have an equivalent of jQuery's document ready.
Here's the prototype equivalent:
document.observe("dom:loaded", function() {
// do stuff
});
Try putting your code in load event:
$(window).load(function(){
$("#xxx").fooBar = function() { ... };
});
If the code has to be directly before the input, you can check if it has loaded after a certain period of time.
<script type="text/javascript">
//Sets up a function to execute once the input is loaded
f = function ()
{
//Checks if 'xxx' exists (may vary between frameworks)
if ($("xxx") !== undefined)
{
$("xxx").fooBar = function() { ... };
//Escapes the timer function, preventing it from running again
return true;
}
//If still not loaded check again in half a second (0.5s or 500ms)
setTimeout(f,500);
return false;
}
f();//Initialize the timer function
</script>
<input id="xxx" .../>
Instead of adding a method to the dom node, why not make it a separate function, so instead of
$("xxx").fooBar = function() {
doStuff(this);
};
you would have something like
function xxx_fooBar () {
var me = document.getElementById('xxx');
doStuff(me);
};
Another suggestion: If you can add attributes to the <input> element, you could do something like this...
<script>
function xxx_init (e) {
e.fooBar = function () {
doStuff(this);
};
}
</script>
<input onload="xxx_init(this)" id="xxx" .../>
Or you could do as others suggest and attach the scripts to the window.onload event.

Categories