html - javascript change text to element's alt text on hover -
i've got series of images, and, upon hover, i'd them change text of <span>
element. accomplished before redundant javascript, changing text of <span>
on every onmousein , onmouseout every image, each unique id. used code, repeated several times:
window.onload = function () { document.getelementbyid("foo").onmouseover = function () { document.getelementbyid("element").innerhtml = "bar"; }; document.getelementbyid("foo").onmouseout = function () { document.getelementbyid("element").innerhtml = "bar"; };
but wondering if there easier way this, using alt
tag of image. on image hover, i'd want <span>
tag display hovered image's alt
text, , onmouseout, go normal. how done? thanks.
you elements in page using tag name below , add event handlers
window.onload = function() { var imgs = document.getelementsbytagname('img'), span = document.getelementbyid("element"); (var = 0; < imgs.length; i++) { imgs[i].addeventlistener('mouseenter', function() { span.innerhtml = this.alt || ''; }); imgs[i].addeventlistener('mouseleave', function() { span.innerhtml = ''; }); } }
<span id="element"></span> <br /> <img src="//placehold.it/64x64&text=1" alt="img 1" /> <img src="//placehold.it/64x64&text=2" alt="img 2" /> <img src="//placehold.it/64x64&text=3" alt="img 3" /> <img src="//placehold.it/64x64&text=4" alt="img 4" />
if don't want target img element, can add class images need trigger it, use document.getelementsbyclassname('classname')
instead of document.getelementsbytagname('img')
Comments
Post a Comment