yonige yonige - 1 year ago 100
HTML Question

JavaScript - How to show image ALT text on a div?

I'm trying to show the alt text of those images on the "show" div. I want to click an image and show its alt on the div, click another image and show its alt... Something like that. But I can't make it work.

<div id="IMGS">
<div><img src="img/frog.jpg" alt="this is a frog" height="100" /><p>0</p></div>
<div><img src="img/bird.jpg" alt="this is a bird" height="100" /><p>0</p></div>
<div><img src="img/Photoshop-01.jpg" alt="this ain't real" height="100" /><p>0</p></div>
<div id="show"></div>

Answer Source

In this code, you add an event listener for each image:

var myImage = document.getElementsByTagName("img");
    for (var i = 0; i < myImage.length; i++) {

function show(){
    var myAlt = this.alt;
    var text = document.getElementById("show");
    text.innerHTML = myAlt;

Check the working fiddle: https://jsfiddle.net/gerardofurtado/2bkkr6g6/

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download