Martin Martin - 7 months ago 25
HTML Question

Display image Alt Attribute text on hover

I'd like to know how to display

alt
text of
img
, inside of
p
element on mouse hover.

Here's my HTML:

<img src="img1.jpg" alt="one"/>
<img src="img2.jpg" alt="two"/>
<img src="img3.jpg" alt="three"/>

<p id="text"> </p>


And JS:

function showAlt(){
var img = document.getElementsByTagName("img");
var text = document.getElementById("text");

for(var i=0; i < img.length; i++){
img[i].addEventListener("mouseover", function(){
var alt = img[i].alt;
alt.appendChild(text);}}

}


And JSfiddle: here

Answer

You can change text of p element with textContent DEMO

var img = document.getElementsByTagName("img");
var text = document.getElementById("text");

for (var i = 0; i < img.length; i++) {
  img[i].addEventListener("mouseover", function() {
    var alt = this.alt;
    text.textContent = alt;
  });
}

If you want to remove text on mouseleave you can add another event and change text to empty string DEMO