I am currently developing Unit Tests for a Javascript method that detects the readiness of the document. This code is already at framework level, so please avoid mentions of this being already implemented in jQuery or another library.
I have successfully simulated the 'readystatechange' change event with the following code:
var event;
event = document.createEventObject();
event.type = 'readystatechange';
document.fireEvent('onreadystatechange',event);
I failed to do the same for the 'load' event. The following code results in an invalid argument error in IE7, thrown by the call to fireEvent on the last line:
event = document.createEventObject();
event.type = 'load';
document.fireEvent('onload',event);
Has anyone done this, or failed to do this before? I am also interested in any suggestion to fire the event in a different way.
Edit: following the suggestion by Crescent Fresh, I changed my code to:
event = document.createEventObject();
event.type = 'load';
document.body.fireEvent('onload',event);
There is no more error, but the listener for 'onload' does not fire. Here is how I configured it:
document.attachEvent('onload',listener);
According to this page at MSDN, there's no onload event for document.
You want either window.onload or document.body.onload. These are identical in IE: for historical reasons, <body onload="..."> actually sets window.onload, so MS decided to make document.body.onload an alias of window.onload.
The problem with this is - as Eric mentioned in the comments - that there doesn't seem to be a way to manually fire window events, which means that there might not be a solution for Eric's problem.
For some reason, it appears that IE overrides the onload property of window with an empty object after the DOM is loaded. At least that is the case when you try to access it from within any event handler of a DOM element...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<script type="text/javascript">
window.onload = function() {
alert("Test");
}
alert(typeof window.onload);
</script>
</head>
<body>
<h1 onclick="alert(typeof window.onload);">Test</h1>
</body>
</html>
In this situation, you'll see that window.onload is recognized as a function initially, then you see the "Test" alert. When you click on the heading, you'll see that window.onload is now an object. I tried iterating through the properties of the object, but it's empty. This is not cool.
One lame workaround is to grab the function in the accessible scope and assign it to a different property that you can fire at your convenience...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<script type="text/javascript">
window.onload = function() {
alert("Test");
}
</script>
</head>
<body>
<h1 onclick="window.onloadfix()">Test</h1>
<!-- Could potentially be injected via server-side include if needed -->
<script type="text/javascript">
window.onloadfix = function() {
window.onload();
}
</script>
</body>
</html>
I can't think of any other way to address this issue right now.
The load event will fire when the document (including external resources such as images) has fully loaded, and not before.
What results are you getting from your attempts to fire readystatechange? Does the readyState value actually change at all? Whether or not, that's not of much use either: either you fire the event with a readyState that hasn't changed, or you do so with a readyState that isn't a valid reflection of the state of the document.
Related
<!DOCTYPE html>
<html>
<head>
<script>
function init() {
document.getElementById("inputname").id = 'newinputname';
document.getElementById("newinputname").onchange = function() { Test() };
}
function Test() {
alert('Test');
}
</script>
</head>
<body onload='init()'>
Enter your name: <input type="text" id="inputname">
</body>
</html>
I can't to seem to find any way of viewing the altered page. For example in the above example, which has no purpose other than to illustrate, I would like to be able to see the effect of the onchange reflected. With say IE and F12 tools I can see the name change to the input element but can't see the onchange anywhere.
I have a piece of code which alters a table significantly, changes ids and sets onclick handlers. I would like to check that the changes have gone through. As above I can see the id alterations etc have worked OK and the onclick functions seem to work OK but I can't see where the onclick="..." has been entered in the new page output.
I think I may have some basic misunderstanding. Any help gratefully received.
Rather than adding attribute onchange, assigning document.getElementById("newinputname").onchange sets new event listener.
If you want to see events connected to element, you will have to use console.log and similar tools. See this answer: How to find event listeners on a DOM node when debugging or from the JavaScript code?
<HTML>
<HEAD>
<TITLE>Statements with returnValue</TITLE>
</HEAD>
<BODY>
Drive C
</BODY>
</HTML>
Question:
We have this line: event.returnValue=false; but why alert() still got excuted? then, what is the purpose to use event.returnValue=false;?
There are two ways to prevent the default behaviour of the click (in this case, navigating to "c:"):
return false from the event handler. This will immediately exit the current event handler, and prevent any further actions.
Set event.returnValue = false. This does not immediately stop the current event handler (ie. onclick), but once it completes, any further actions will be prevented.
Since event.returnValue is not supported in all browsers, I'd definitely recommend using return false instead - just don't forget that it needs to be at the end of your onclick handler.
The purpose of event.returnValue is here: MSDN
It does not, however, change the execution order. You would need to have a return statement to change the order of execution:
<HTML>
<HEAD>
<TITLE>Statements with returnValue</TITLE>
</HEAD>
<BODY>
Drive C
</BODY>
</HTML>
I have a really strange problem. My example code works [here][1] quite fine, but I have the exactly same code in my aptana studio editor and when I try it in Chrome or the Eclipse browser the events just don't fire. I can't imagine what's the problem, because it's exactly the same code ...
HTML
<!DOCTYPE html>
<html>
<head>
<title>OrderScreen</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script src="js/script.js" type="text/javascript"></script>
</head>
<body>
Test
</body>
</html>
jQuery
$("a").mouseup(function() {
clearTimeout(pressTimer);
// Clear timeout
return false;
}).mousedown(function() {
// Set timeout
pressTimer = window.setTimeout(function() {
alert("hcbdhaf")
}, 1000);
return false;
}).click(function() {
alert("dfsdg");
});
If your code is really as quoted, the problem is that the elements don't exist as of when you try to hook event handlers to them. jsFiddle's default settings hide this problem from you. (Look on the left, and you'll see that your code isn't run until the load event fires — which is very, very late in the page load process.)
To fix it, either:
Move your script tags to the end of your document, just before or after the closing </body> tag. By the time the browser runs your script, the elements will exist. This is the recommendation of the YUI team and Google's web engineers like it too.
Use jQuery's ready event.
In conjunction with either of those, you might also look at using event delegation instead of directly hooking up events on the elements. Your mouseup and mousedown handlers will get attached to each a element individually. That's a lot of hookups. If there's a container that all of those a elements are in (body or better yet, something nearer), you might instead hook the event on that container (since those events bubble) and then check to see if the event originated in an a element. jQuery supports event delegation, doing most of the hard work for you, via delegate (which I like because it's so explicit) and more recently, one of the half-dozen variations of arguments you pass to on.
I thinkg I doing something wrong, but the events only works if the selector is document. Otherwise, not happens.
HTML
<html>
<head>
<!-- the libraries references here -->
</head>
<body>
<div id="canvas"></div>
</body>
</html>
Javascript
/* Click on canvas */
canvasClickEvent = function(e){
if(e.shiftKey){
selectedElement = $(this).attr("id");
}
}
/* Events */
$(document).ready(documentLoadEvent);
$(document).click(canvasClickEvent); //this works, but is wrong
//$("#canvas").click(canvasClickEvent); --this is what I want, but not works
$(document).dblclick(canvasDblClickEvent);
If I replace the document by the div name like $('#canvas').click(canvasClickEvent);, the click event is not called. It's only works if the selector is document, but the element passed to the function always has the attibs like undefined.
What might be happening?
What is happening is that event is attempting to bind the event before the DOM element exists.
If you wrap the events inside of the ready() method you guarantee that the domain exists before your event attempts to bind.
$(document).ready( function () {
$("#canvas").click(canvasClickEvent);
}
The ready() method is dependent on the browsers DOMContentLoaded event which basically means the DOM is completely loaded in the browser, but does not necessarily mean all the media on the page has completely loaded. Once all media is loaded the onLoad browser event fires.
It seems like you put your JavaScript code BEFORE the html code. So, when the JavaScript code runs, the elements to be dealt with is not loaded into the DOM yet. (That's why you got "undefined")
Just put your script AFTER the related HTML code. Or put it inside the pageLoad event:
$(function(){
....
})
My main HTML page does the following:
var popup = window.open(...);
// Wait for popup to load
popup.onload = function() { do_something(); };
popup.location = "new-page.html";
I'd like do_something to be called when new-page.html is finished loading. But what I currently have doesn't work -- do_something is never called.
How can I make this work?
I only care about getting this to work in Firefox 3.5, if that makes things easier.
you could use window.opener.<functionName> and put your notification code within that function on the parent page
Have you tried using the opener object?
http://www.webreference.com/js/tutorial1/opener.html
Or, without messing with the HTML of the child window, from the parent, you can attach a listener on the load event of the iframe. In this solution, i am going to use jQuery for simplicty, but any library or even manual event attachment will do.
In the parent's HTML:
<iframe id="foo"></iframe>
<script type='text/javascript'>
var element = $("#foo");
element.load( function( eventObject ) {
// do something here
} );
// Now that the event listener is attached, we can set the source.
element[0].src = "foo.html";
</script>
Note, I have not tried setting the source first and then attaching the listener, I am not sure if this would be guaranteed to always work. It could happen that the iframe is created/loaded before the load listener is attached, I am not sure. But, by setting the src after the listener is attached, I am sure that the load listener will be called.
Shane
http://www.shanetomlinson.com
http://www.ubernote.com
Try having the doSomething method called in the popup's onload. You can refer back to the parent by using window.opener
In your .html that is loaded you could have a simple one liner at the end that calls a function on the opening window (if it exists)
<script type='text/javascript'>
if (window.opener && window.opener.do_something) window.opener.do_something(window);
</script>