is there a way to code this so it will work for IE8 and up, I am trying to find a JQuery solution avoid a check on the browser... (addEventListener does not work in IE8)
document.addEventListener('readystatechange', function () { alert("foo"); })
is there a way to code this so it will work for IE8 and up, I am trying to find a JQuery solution avoid a check on the browser... (addEventListener does not work in IE8)
document.addEventListener('readystatechange', function () { alert("foo"); })
Here's a simple cross browser event function that will work in versions of IE back to IE6 and in all other browsers:
// add event cross browser
function addEvent(elem, event, fn) {
if (elem.addEventListener) {
elem.addEventListener(event, fn, false);
} else {
elem.attachEvent("on" + event, function() {
// set the this pointer same as addEventListener when fn is called
return(fn.call(elem, window.event));
});
}
}
addEvent(document, 'readystatechange', function() {
alert("got it!");
});
Of course, if you already have jQuery, you can just use:
$(document).ready(function() {
alert("got it");
});
And this will automatically handle all sorts of browser versions for you.
FYI, there's a full substitute for jQuery's .ready()
in plain javascript here if you're really trying to get the best DOM loaded detection without jQuery. After including that function, you would just use:
docReady(function() {
alert("got it");
});
If you're using jQuery, you shouldn't need to call addEventListener
directly. Use on
:
$(document).on("readystatechange", function() {
alert("foo");
});
jQuery handles all the browser dependencies for you, that's one of the reasons we use it.