I've got a series of images, and, upon hover, I'd like them to change the text of a <span>
element. I accomplished this before with some very redundant javascript, changing the text of the <span>
on every onMouseIn and onMouseOut for every image, each with a unique ID. I used this 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 I was wondering if there was an easier way to do this, using the alt
tag of the image. On image hover, I'd want the <span>
tag to display the hovered image's alt
text, and onMouseOut, go back to normal. How would this be done? Thanks.
You could get all elements in the page using tag name as below and add the event handlers
window.onload = function() {
var imgs = document.getElementsByTagName('img'),
span = document.getElementById("element");
for (var i = 0; i < 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 you don't want to target all the img element, then you can add a class to all the images which need to trigger it, then use document.getElementsByClassName('classname')
instead of document.getElementsByTagName('img')