add event to all image elements using javascript

add event to all image elements using javascript

In this article we will show to attach event to DOM element and add event to all image elements using javascript. Using javascript we can attach the event to any dom element.

add event to all image elements using javascript

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.


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>
add event to all image elements using javascript
add event to all image elements using javascript

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)

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

Leave a Reply

Your email address will not be published.