Click button on load event - javascript

I have the following javascript -
function onLoad() {
if (!(document.applets && document.VLVChart && document.VLVChart.isActive())) {
setTimeout('onLoad()', 200);
return;
}
objChart = document.VLVChart;
PollEvent();
}
function fan() {
objChart.reorganize();
}
And then when the HTML page is loaded -
<body onLoad="onLoad()">
and have a button within the HTML that execute the fan() function -
<input type='button' value='Fan' onClick='fan();'>
Is it possible for me to activate the fan() function within the onload event so that a user does ont have to click the button?
EDIT
After trying the provided answers, on debugging the code breaks on the line -
objChart.reorganize();
Within the fan() function with the error -
SCRIPT5007: Unable to get value of the property 'reorganize': object is null or undefined
This is odd as when I manually click the button on the page, the function works fine.
Solution
After much head scratching I have realised that I was trying to load the fan() function before the page (and more specifically the objChart) had fully loaded. Hence why adding the function in the onLoad event was not working. I added a setTimeout -
function Fan()
{
setTimeout(function(){objChart.reorganize();},3000);
}

<body onload='onLoad(); fan();'>...
However inline JS is best avoided and you would do well to begin looking into centralised event management. There are various advantages to this.
An answer I wrote yesterday to another question outlines why this is. Something like jQuery makes this trivial if it's new for you.
$(function() {
$('body').on('load', function() {
onLoad();
fan();
});
});

Reading your question I assume you didn't even have tried. Just call that function from within your onLoad()-function:
function onLoad()
{
fan();
/* … */
}

Yes.
You can use <body onload='onLoad(); fan();'> as Utkanos suggests.
If you use jQuery, you can also stick a script in the head containing:
$(function(){
...
});
The jQuery function actually fires earlier, as is explained here.

Related

Only part of JQuery executable. When pasted in HTML directly everything works (window.location)

I have a JS file, which works flawlessly, and executes all the code in it.
But I now added the following JQuery:
$("#need2Know").click(function(){
window.location ="URLString";
return false;
});
$("#nice2Know").click(function(){
window.location ="URLString";
return false;
});
When I call this part of the code in the HTML file, the onclick Handling executes as expected.
However, as soon as I paste it in the JS file (above all other code, the remainder of the code still working), the onclick handling does not work anymore.
I use the following JQuery library:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
My JQ file is called after this library.
What is so strange to me is, that the code works in HTML but not in the JS file, although the rest of the code still processes as before...
Any advice on how to fix this, so the click-handling can be performed in the JS?
Currently what you are using is called a "direct" binding which will only attach to element that exist on the page at the time your code makes the event binding call. As the DOM is not loaded yet, no event handlers are attached.
You can solve the problem by one of these methods:
Wrap the code in document-ready handler.
Specify a function to execute when the DOM is fully loaded.
$(document).ready(function() {
});
Move the reference to the file to bottom of the <body> element.
Try this code:
$("body").on("click","#nice2Know", function(){
window.location ="URLString";
return false;
});

JavaScript code is not executed during the runtime of the code, but when I debug it and execute in console, it works

I have a following code:
var e = document.getElementById("overlay");
e.parentNode.removeChild(e);
This code is supposed to remove the DOM element, but it doesn't. So I removed the code and added a breakpoint in its stead and input the code in the console during the pause manually, and it worked (i.e. the element was successfully removed).
This behavior seems rather strange for me, so I wanted to ask, why does it happen and what can I do to inspect this peculiar issue?
Thanks in advance.
EDIT: Thanks for quick replies. Nonetheless, I want to make it perfectly clear that the element #overlay does exist at the time of the execution of the code. Moreover, when I put a debugging breakpoint at that place in the code and execute these two lines of code, it does have an effect on this particular existent element (which it doesn't without debugging).
EDIT 2: I was asked to clarify the code. I execute the following code before the body (part of the queryloader2 plugin, which ensures image preloading):
window.addEventListener('DOMContentLoaded', function() {
new QueryLoader2(document.querySelector("body"), {});
});
No errors present (except for a 404 error because of missing image, which has no impact on Javascript).
As Teemu mentioned #overlay more than likely doesn't exist when the code is run.
For a test.. Try wrapping your code in either of these...
Javscript
window.onload = function () { /*your code*/ };
Jquery (if included)
$(document).ready(function () { /* your code*/ });
You should execute your code after the DOM tree has finished loading. One option is to wrap your code in a function that executes after the DOMContentLoaded event has been fired.
document.addEventListener("DOMContentLoaded", function(event) {
// your code
});
Look at this answer for more information: $(document).ready equivalent without jQuery

`window.open` function dosen't open a popup windo but do vanish the existing html and other code

i have a very simple code which tries to open a popup window but it passes to ruin the whole html and other code.
the code is as follows:
<head>
<script type="text/javascript">
function write(){
/* var w = String(window.offsetWidth),
s = String(window.offsetHeight);*/
var s = window.open('', 'MsgWindow', '_blank');
};
</script>
</head>
<body>
<button onclick="write();" id="writeBtn">Write</button>
</body>
so simple but it dosent do anything!
i don't know what is the problem.
something to note...
when the button is clicked then the screen goes white and all the element disappear
when i saw this in google console then what i saw was shocking all the html code just disappear
i even try to werite in to the variable s like s.document.write('sanmveg') but that dosen't worked
what is the problem?
Rename your function. document.write() is being called instead of your function. Calling document.write() with no parameters causes unexpected behavior like this.
function mywrite() {
var s = window.open('', 'MsgWindow');
};
<button onclick="mywrite();" id="writeBtn">Write</button>
The problem is that your write function isn't being called; instead, document.write is being called. The reason for this is somewhat complex, but the short version is: If you call your function something else that isn't on document (or button elements), like openwindow, it'll work.
So why is document.write being called even though you're calling write(), expecting it to pick up your global write function?
Attribute-based onxyz event handlers are called in a complex scope which is effectively a series of nested with statements, each mixing in different stuff, and one of the things in that mix is the document object.
When you use an attribute-based onxyz event handler on a button as you have in your code, the browser generates a handler for you that looks very roughly like this:
with (document) {
with (theButton) {
handler = function() {
/* This is your attribute text */
write();
/* This is the end of your attribute text */
};
}
}
...and then calls the handler function. So when the browser calls your function, it tries to resolve any free symbols in your function, like write, against the button element first, then if the button doesn't have a write it tries document, and then if document doesn't have it, it tries the global scope.
But of course, document does have a write function, so it gets called instead of your event handler.
You can actually see this in Chrome, or Firefox with Firebug, by doing this:
Create a button with debugger; in the onclick, e.g.:
<button onclick="debugger;">Click Me</button>
Open the page in your browser
Open your dev tools / Firebug
Click the button
At this point, the debugger will pop up, paused on the debugger; statement. Here's what you see in Chrome:
(I don't know what the object is that Chrome inserts between the document and the button; it'll be a Chrome-specific implementation detail.)
And in Firefox+Firebug:
You can see how the function is nested within a couple of with blocks.
If your button were inside a form, the form would be there too, like this:
with (document) {
with (theForm) {
with (theButton) {
handler = function() {
/* This is your attribute text */
write();
/* This is the end of your attribute text */
};
}
}
}
...and so free symbols would attempt to resolve against the form element.
I guess you should fill the arguments in the proper order , which is :
window.open( "URL" , "window name" , "menubar,resizable,width,height,top,left") ;
note that the third argument should be a comma-separated string that specify some properties

How to execute code before window.load and after DOM has been loaded?

Here is the circumstance:
I have 2 pages:
1 x html page
1 x external Javascript
Now in the html page, there will be internal Javascript coding to allow the placement of the window.onload, and other page specific methods/functions.
But, in the external Javascript I want certain things to be done before the window.onload event is triggered. This is to allow customized components to be initialized first.
Is there a way to ensure initialization to occur in the external Javascript before the window.onload event is triggered?
The reason I have asked this, is to attempt to make reusable code (build once - use all over), to which the external script must check that it is in 'order/check' before the Javascript in the main html/jsp/asp/PHP page takes over. And also I am not looking for a solution in jQuery #_#
Here are some of the links on Stack Overflow I have browsed through for a solution:
Javascript - How to detect if document has loaded (IE 7/Firefox 3)
How to check if page has FULLY loaded(scripts and all)?
Execute Javascript When Page Has Fully Loaded
Can someone help or direct me to a solution, your help will be muchness of greatness appreciated.
[updated response - 19 November 2012]
Hi all, thanks for you advice and suggested solutions, they have all been useful in the search and testing for a viable solution.
Though I feel that I am not 100% satisfied with my own results, I know your advice and help has moved me closer to a solution, and may indeed aid others in a similar situation.
Here is what I have come up with:
test_page.html
<html>
<head>
<title></title>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript" src="test_script_1.js"></script>
<script type="text/javascript" src="test_script_2.js"></script>
<script type="text/javascript">
window.onload = function() {
document.getElementById("div_1").innerHTML = "window.onload complete!";
}
</script>
<style type="text/css">
div {
border:thin solid #000000;
width:500px;
}
</head>
<body>
<div id="div_1"></div>
<br/><br/>
<div id="div_2"></div>
<br/><br/>
<div id="div_3"></div>
</body>
</html>
loader.js
var Loader = {
methods_arr : [],
init_Loader : new function() {
document.onreadystatechange = function(e) {
if (document.readyState == "complete") {
for (var i = 0; i < Loader.methods_arr.length; i++) {
Loader.method_arr[i]();
}
}
}
},
load : function(method) {
Loader.methods_arr.push(method);
}
}
test_script_1.js
Loader.load(function(){initTestScript1();});
function initTestScript1() {
document.getElementById("div_1").innerHTML = "Test Script 1 Initialized!";
}
test_script_2.js
Loader.load(function(){initTestScript2();});
function initTestScript2() {
document.getElementById("div_2").innerHTML = "Test Script 2 Initialized!";
}
This will ensure that scripts are invoked before invocation of the window.onload event handler, but also ensuring that the document is rendered first.
What do you think of this possible solution?
Thanking you all again for the aid and help :D
Basically, you're looking for this:
document.onreadystatechange = function(e)
{
if (document.readyState === 'complete')
{
//dom is ready, window.onload fires later
}
};
window.onload = function(e)
{
//document.readyState will be complete, it's one of the requirements for the window.onload event to be fired
//do stuff for when everything is loaded
};
see MDN for more details.
Do keep in mind that the DOM might be loaded here, but that doesn't mean that the external js file has been loaded, so you might not have access to all the functions/objects that are defined in that script. If you want to check for that, you'll have to use window.onload, to ensure that all external resources have been loaded, too.
So, basically, in your external script, you'll be needing 2 event handlers: one for the readystatechange, which does what you need to be done on DOMready, and a window.onload, which will, by definition, be fired after the document is ready. (this checks if the page is fully loaded).
Just so you know, in IE<9 window.onload causes a memory leak (because the DOM and the JScript engine are two separate entities, the window object never gets unloaded fully, and the listener isn't GC'ed). There is a way to fix this, which I've posted here, it's quite verbose, though, but just so you know...
If you want something to be done right away without waiting for any event then you can just do it in the JavaScript - you don't have to do anything for your code to run right away, just don't do anything that would make your code wait. So it's actually easier than waiting for events.
For example if you have this HTML:
<div id=one></div>
<script src="your-script.js"></script>
<div id=two></div>
then whatever code is in your-script.js will be run after the div with id=one but before the div with id=two is parsed. Just don't register event callbacks but do what you need right away in your JavaScript.
javascript runs from top to bottom. this means.. if you include your external javascript before your internal javascript it would simply run before the internal javascript runs.
It is also possible to use the DOMContentLoaded event of the Window interface.
addEventListener("DOMContentLoaded", function() {
// Your code goes here
});
The above code is actually adding the event listener to the window object, though it's not qualified as window.addEventListener because the window object is also the global scope of JavaScript code in webpages.
DOMContentLoaded happens before load, when images and other parts of the webpage aren't still fully loaded. However, all the elements added to the DOM within the initial call stack are guaranteed to be already added to their parents prior to this event.
You can find the official documentation here.

JQM .bind function call hangs on a method, but script still completes

I'm just getting started with Javascript, jQuery, and jQuery Mobile. I'm trying to go through a tutorial online, but I'm getting caught up on the mobileinit event handler. Here is the code:
<script type="text/javascript">
$(document).bind("mobileinit", function() {
Notes.testHelper.createDumyNotes();
Notes.controller.init();
});
</script>
If I put an alert before and right after Notes.testHelper.createDummyNotes(); the alert is called. However, if I put the alert right after Notes.controller.init(), the alert isn't called. I imagine this means the code stopped in that function. However, if I put an alert right before the closing script tag outside of the function, that alert is called--This is what confuses me. How can a method hang and not allow the rest of a function to complete but still let the script complete?
As an interesting aside, I forgot to put the script tags around this .bind function at first, and the html was styled correctly. However, once I put the tags around this function, the html appeared but wasn't styled.
Any suggestions? As I said, I'm new to javascript, so this could be a fundamental misunderstanding of the way the language executes.
Thanks for your help!
The contents of $(document).bind("mobileinit", function() { ... } will be called when the mobileinit event is triggered, which will be AFTER the code between the script tags are read. This is why the alert you placed just before the closing script tag is executed.
If you put alert(1); before the closing tag, and alert(2); after the function() { and alert(3) after the createDumyNotes(), you will probably get 1 and 2 but not 3.
I think you're on the right path in that the error is occurring in the createDumyNotes() function. I suggest you get into that function with some try { ... } catch(e) { ... } and pinpoint where the error is occurring (assuming Notes and Notes.testHelper are valid objects, and Notes.testHelper.createDumyNotes() is an existing function.
EDIT
I just noticed that your function is createDumyNotes() instead of createDummyNotes(). Is this nothing more than a misspelling?

Categories