4196

how to trigger mouseover event only for an img element using javascript

Question:

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?

Answer1:

I think you should apply event listeners to elements one by one:

<pre class="snippet-code-js lang-js prettyprint-override">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) <pre class="snippet-code-html lang-html prettyprint-override"><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:

<pre class="snippet-code-js lang-js prettyprint-override">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) <pre class="snippet-code-html lang-html prettyprint-override"><img src="" width="90" height="80"> <img src="" width="90" height="80"> <img src="" width="90" height="80">

Answer2:

getElementsByTagName returns a live <a href="https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection" rel="nofollow">HTMLCollection</a> 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) {}; }

Answer3:

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){ }

Answer4:

Would any of these do what you want? You would need <a href="https://jquery.com/" rel="nofollow">JQuery</a> for it, but I'd recommend it anyway.

$('#img') .mousemove(function (event) { console.log('Mouse moved'); }) .mouseenter(function () { console.log('Mouse over'); })

Recommend

  • display a overlay when input is clicked in react
  • avoid automatic jump to bottom on page with iframe video
  • javascript variables, What does var x = a = {} do?
  • Can a variable be stored within an image or div tag?
  • button in popup.html not working
  • Function JavaScript : on Menu CSS HTML
  • Select inner HTML item in CSS
  • Making header act like google chrome mobile app address bar
  • How to add closing tag for canvas in three js rendered Canvas?
  • Cut the background to expose the layer below
  • Sonar maven jacoco code coverage for Multimodule project
  • Adjust width of select element according to selected option's width
  • how to display data from 1st point on words on y axis for line chart in d3.js
  • Custom validator control occupying space even though display set to dynamic
  • How do I alternate colors in Flat List (React Native)
  • Listbox within Listbox and scrolling trouble in Windows Phone 7 Silverlight
  • Highlight and Bold text in JTextPane
  • Change multiple background-images with jQuery
  • Repeat a vertical line on every page in Report Builder / SSRS
  • Xamarin Forms - UWP Fonts
  • Change JButton Shape while respecting Look And Feel
  • How to convert from System.Drawing.Color to Excel.ColorFormat in C#? Change comment color
  • Why doesn't :active or :focus work on text links in webkit? (safari & chrome)
  • Shallow update not allowed (git > 1.9)
  • How can I use Kendo UI with Razor?
  • Change an a tag attribute in JavaScript based on screen width
  • jquery mobile loadPage not working
  • Rearranging Cells in UITableView Bug & Saving Changes
  • Unanticipated behavior
  • How to include full .NET prerequisite for Wix Burn installer
  • Benchmarking RAM performance - UWP and C#
  • CSS Applying specific rule for a specific monitor resolution with only CSS is posible?
  • Angular 2 constructor injection vs direct access
  • Change div Background jquery
  • Android Google Maps API OnLocationChanged only called once
  • How does Linux kernel interrupt the application?
  • Qt: Run a script BEFORE make
  • IndexOutOfRangeException on multidimensional array despite using GetLength check
  • Busy indicator not showing up in wpf window [duplicate]
  • Why do underscore prefixed variables exist?