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:
- add event to an image javascript
- html attach javascript to image
- add event to an image javascropt
- javascript image add event
- javascript img addevent
- javascript image event 추가
- javascript assign event to all tags
- javascript add event to all tags
- image add event
- add event to an image
- how to ADD an event image javascript
- how to add an event for an image in javascript
- get all img elements javascript
- addeventlistener image javascript
- js attach to image







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