How To Trigger Mouseover Event Only For An Img Element Using Javascript
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
Solution 1:
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">
Solution 2:
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) {};
}
Solution 3:
GetElementsByTagName return the Collection of elements. If the is only one img
it will be the collection with one element. So you need to access property of this collection through [0]
.
document.getElementsByTagName('img')[0].onmouseover=function(e){ }
Solution 4:
Would any of these do what you want? You would need JQuery for it, but I'd recommend it anyway.
$('#img')
.mousemove(function (event) {
console.log('Mouse moved');
})
.mouseenter(function () {
console.log('Mouse over');
})
Post a Comment for "How To Trigger Mouseover Event Only For An Img Element Using Javascript"