In this article I will show show to attach event to DOM element.
You many times heard about getElementsByTagName javascript method but you did not tried.
getElementsByTagName function is very useful when you are working with javascript events. Using this function you can attach the event to any tag which is present in HTML body.
Here I am going to give the image example. Following script will attach the mouseover event to all images which are present in DOM.
<script type="text/javascript">
var all_images = document.getElementsByTagName('img');
for (var i = 0; i < all_images.length; i++) {
addEvent(all_images[i], 'mouseover', myfunction, false);
}
function myfunction () {
alert('this is image mouse over alert');
}
/**
* cross-browser event handling for IE5+, NS6 and Mozilla
* By Scott Andrew
*/
//This addEvent function we are using for external class use
this.addEvent = function(elm, evType, fn, useCapture) {
if (elm.addEventListener) { // Mozilla, Netscape, Firefox
elm.addEventListener(evType, fn, useCapture);
return true;
} else if (elm.attachEvent) { // IE5 +
var r = elm.attachEvent('on' + evType, fn);
return r;
} else {
elm['on' + evType] = fn;
}
}
</script>
If you copy paste the following code in your document and If you mouseover on any image then alert with message will come.
This script will work in any browsers. (IE 6,7,8, FF3,2, Safari3,4)
Incoming search terms:
- attach javascript to image
- event for all tag javascript
- how to add an event in image from javascript
- javascript add event to all elements
- javascript addevent for all images
- javascript events for image tag in ruby
- javascript image added event
- javascript to gety all elements in image
- wp-comments-post addeventlistener







Great information thanks for getting this out there for people like me to read.