Tip: Get the source element of an event

Tuesday, June 17, 2008 at 2:56 PM



Sometimes it's very useful to get a reference to the UI element that triggers a certain event. This way, instead of writing individual event-handler functions for every element, you can just work with event.srcElement.

Let's say we have a couple of labels for which we want to create a hover effect. Simple stuff: when the mouse moves over a label, that label's text turns white; when the mouse exits, the text turns black. We can accomplish this behavior by using one function to handle both labels' onmouseover events and another to handle their onmouseout events. The functions look like this:
function _onMouseOver(){
event.srcElement.color="#FFFFFF";
}

function _onMouseOut(){
event.srcElement.color="#000000";
}
You can see the results in this sample gadget.

Have a tip you'd like to share? Send it to gd-developer AT google DOT com. To see all tips, choose the Tips label.

No comments: