JavaScript tip: Use a for-loop to reveal properties and methods
I’ve been tinkering with the HTML5 video element quite a bit lately. However, it’s not the best-documented thing in the world. There are very useful properties in the video element’s events that aren’t so clearly explained in the spec. Developing a media player means you have to uncover these properties using a little bit of scripting know-how.
Luckily for us, there is a very easy way to reveal the methods and properties of just about any element in the DOM. Experienced JavaScript developers probably know this. It’s possibly one of the most useful things you can know about using JavaScript: use a for-loop to reveal an object’s unknown properties and methods.
Let’s assume you have a div with an id value of “test.” Let’s also assume that you have Firebug, for Firefox installed (and enabled), or that you have enabled developer tools in Safari (this may work with Opera‘s Dragonfly as well).
To find out the properties and methods, for “test,” you would use the following code:
var p; // initialize this variable.
var testElement = document.getElementById('test');
for(p in testElement){
console.log( p +': '+testElement[p] ); // using array notation for objects, which works just fine.
}
In Firebug, the output will look a bit like this:
That’s a list of every property and every method — and whether or not it’s a native part of the DOM (as supported by the browser) — available for this object.
Similarly, you can do the same thing with an event. Consider:
function clickHandler(evt){
var p;
for(p in evt){
console.log( p+': '+evt[p] );
}
}
testElement.addEventListener('click',clickHandler,false);
The code above would reveal all of the properties of the event listener (note that in Internet Explorer, you would use the attachEvent() method). This is how I learned that in Firefox, the progress event of the video element contains both “total” and “loaded” properties — which will come in handy for creating a loading progress display.
Now if you don’t use Firefox with Firebug, Safari (or Opera), you can also output the data to a <div> in your HTML page.
