JIMMY JIMMY - 5 months ago 13
HTML Question

How to highlight the clicked image and show the name of it in a list

There are images. When I click on one of them I want to highlight it and display the name of it in a list.

HTML

<img class="high" id="x" src="images/Chrysanthemum.jpg" alt="Chrysanthemum" width="300" height="200" onclick="mySelect()">


JS

function mySelect() {
document.getElementById("x").style.border = "3px dotted blue";
}


I'm using this code to highlight. But when I click on any image it doesn't highlight. It only highlights the first image.

example image

When I click on an image it should highlight. And the name of it should show up in the corresponding
<li>
.

When I click on another image it should highlight this one and unhighlight the one before. And the name of the corresponding
<li>
should be replaced with the placeholder.

Answer

There are two things to do:

  1. Toggle class name
  2. Swap li.innerHTML with img.alt

    // List.children.lenght and imgs.children.length must always be the same!
    
    var imgs = document.getElementById("images");
    var list = document.getElementById("list");
    var cN = "active";
    
    for (var i = 0; i < imgs.children.length; i += 1) {
        (function(i) {
            imgs.children[i].addEventListener("click", function() {
                this.className === "" ? this.className = cN : this.className = ""; // Toggle class name
    
                // Swap img.alt with li.innerHTML
                var temp = list.children[i].innerHTML;
                list.children[i].innerHTML = this.alt;
                this.alt = temp;
            });
        })(i);
    }
    

Complete example:

// List.children.lenght and imgs.children.length must always be the same!

var imgs = document.getElementById("images");
var list = document.getElementById("list");
var cN = "active";

for (var i = 0; i < imgs.children.length; i += 1) {
    (function(i) {
        imgs.children[i].addEventListener("click", function() {
            // Toggle class name
            this.className === "" ? this.className = cN : this.className = ""; 

            // Swap img.alt with li.innerHTML
            var temp = list.children[i].innerHTML;
            list.children[i].innerHTML = this.alt;
            this.alt = temp;
        });
    })(i);
}
.container ul {
    padding: 0;
    list-style: none;
}

.container ul,
.container #images {
    float: left;
    margin: 15px;
}

.container #images img:hover {
    cursor: pointer;
}

.active {
    border: 3px dotted brown;
}
<div class="container">
    <ul id="list">
        <li>Image1</li>
        <li>Image2</li>
        <li>Image3</li>
    </ul>
    <div id="images">
        <img src="http://unsplash.it/100/70?image=10" alt="Title 1">
        <img src="http://unsplash.it/100/70?image=15" alt="Title 2">
        <img src="http://unsplash.it/100/70?image=20" alt="Title 3">
    </div>
</div>

Comments