Showing posts with label Event Targets. Show all posts
Showing posts with label Event Targets. Show all posts

07/01/2009

JavaScript: Event Target

A simple way to get the element that starts an event. I'm using this to ascertain which text box is calling the KeyPress event in pure JavaScript:

function KeyPress(event) {
var srcElement = getElement(event);
alert(srcElement.id);
}

function getElement(evt) {
if (window.event)
return window.event.srcElement;
else
return evt.currentTarget;
};

Another variation of this script could be written as such (note, this get's the object that triggers the event):

function getTargetElement(evt){
if (window.event)
return window.event.srcElement;
else
return evt.target;
}

Over and Out