I want my mouseover event to only trigger when I hover over an img element only. I used
document.getElementsByTagName('img').onmouseover=function(e){ }
but it doesn't works. How should i achieve this?
I think you should apply event listeners to elements one by one:
const imgs = document.getElementsByTagName('img');
const map = fn => x => Array.prototype.map.call(x, fn);
map(img => {
img.addEventListener('mouseover', (e) => {
e.target.style.border = '1px solid red';
});
img.addEventListener('mouseleave', (e) => {
e.target.style.border = 'none';
});
})(imgs)
<img src="" width="100" height="100">
<img src="" width="100" height="100">
<img src="" width="100" height="100">
Here we extract map function from the Array.prototype so we can map a function over any iterable object, not just arrays.
The same code with regular ES5 syntax:
const imgs = document.getElementsByTagName('img');
const map = function(fn) {
return function(x) {
Array.prototype.map.call(x, fn);
}
}
const sponge = 'http://vignette3.wikia.nocookie.net/spongebob/images/6/6f/SpongeBob_%286%29.png/revision/latest?cb=20140824163929';
map(function(img) {
img.addEventListener('mouseover', function(e) {
e.target.src = sponge;
});
img.addEventListener('mouseleave', function(e) {
e.target.src = '';
});
})(imgs)
<img src="" width="90" height="80">
<img src="" width="90" height="80">
<img src="" width="90" height="80">
getElementsByTagName returns a live HTMLCollection of elements. You need to set the event on all elements and not on the Collection.
You can do that like :
var arrElem = document.getElementsByTagName('img');
for (var i = arrElem.length; i-- ;) {
arrElem[i].onmouseover = function(e) {};
}
map and other Array.prototype methods as shown in my answer.
getElementsByTagNamereturnArray likeof elements, so you need to loop through in that array, or use index to target one of them