Home > Back-end >  Getting src attribute of clicked image using getElementsByClassName
Getting src attribute of clicked image using getElementsByClassName

Time:09-23

Please i need a little help with my JavaScript Code. I'm working on this assignment. The Project is supposed to an emoji maker.

The idea is to create different emojis by combining of different images (skin, eyes and mouth)

So on image click, the clicked image is supposed to show on the preview div. The skin first, then on top of which eyes and mouth will also be placed(I haven’t effected this with my codes). I’m still trying to get the selected skin to display large across that preview div but keep getting undefined:1 GET file:///C:/Users/Acer/Desktop/emoji maker/undefined net::ERR_FILE_NOT_FOUND

This is my Code

let preview = document.getElementById('final')
let img = document.getElementsByClassName('img')
//appendImageSrc(img);
//console.log(img);
for (var i = 1; i < img.length; i  ) {
  //console.log(img[i]);
  img[i].addEventListener("click", function() {
    let srcs = img.src;
    console.log(preview);
    //img[i].getAttribute('src');
    preview.src = img[i];
  })

}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
  <link href="index.css" rel="stylesheet">
  <title>Emoji maker using Javascript</title>
</head>

<body>
  <div class="container">
    <div class="split left">
      <h2 class="head" style="color: red;"> Emoji Builder</h2>
      <div class="card c1">
        <div class="card-body">
          <h5 class="card-title"> Select Face</h5>
          <img class="img" src="assets/skin/yellow.png" alt="yellow">
          <img class="img" src="assets/skin/red.png" alt="red">
          <img class="img" src="assets/skin/green.png" alt="green">
        </div>
      </div>
      <div class="card c2">
        <div class="card-body">
          <h5 class="card-title"> Select Eyes</h5>
          <img class="img" src="assets/eyes/closed.png" alt="closed">
          <img class="img" src="assets/eyes/normal.png" alt="normal">
          <img class="img" src="assets/eyes/laughing.png" alt="laughing">
          <img class="img" src="assets/eyes/rolling.png" alt="rolling">
          <img class="img" src="assets/eyes/long.png" alt="long">
          <img class="img" src="assets/eyes/winking.png" alt="wink">
        </div>
      </div>
      <div class="card c3">
        <div class="card-body">
          <h5 class="card-title"> Select Mouth</h5>
          <img class="img" src="assets/mouth/open.png" alt="open">
          <img class="img" src="assets/mouth/smiling.png" alt="smiling">
          <img class="img" src="assets/mouth/straight.png" alt="straight">
          <img class="img" src="assets/mouth/sad.png" alt="sad">
          <img class="img" src="assets/mouth/teeth.png" alt="teeth">
        </div>
      </div>
    </div>
  </div>

  <div class="split right">
    <h2 class="head"> preview</h2>
    <div class="centered">
      <div id="preview">
        <img id="final" src="" alt="">
      </div>
    </div>
  </div>
  </div>


  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>

</body>

</html>

This console.log(preview); Prints out <img id ="final" src ="undefined" alt> in the console. What could i be missing?

CodePudding user response:

Instead of img.src try using this.src

let preview = document.getElementById('final')
let img = document.getElementsByClassName('img')
//appendImageSrc(img);
//console.log(img);
for (var i = 1; i < img.length; i  ) {
  //console.log(img[i]);
  img[i].addEventListener("click", function() {
    let srcs = this.src;
    console.log(preview);
    //img[i].getAttribute('src');
    preview.src = srcs;
  })

}
<!doctype html>
<html lang="en">

<head>
  <!-- Required meta tags -->
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-F3w7mX95PdgyTmZZMECAngseQB83DfGTowi0iMjiWaeVhAn4FJkqJByhZMI3AhiU" crossorigin="anonymous">
  <link href="index.css" rel="stylesheet">
  <title>Emoji maker using Javascript</title>
</head>

<body>
  <div class="container">
    <div class="split left">
      <h2 class="head" style="color: red;"> Emoji Builder</h2>
      <div class="card c1">
        <div class="card-body">
          <h5 class="card-title"> Select Face</h5>
          <img class="img" src="assets/skin/yellow.png" alt="yellow">
          <img class="img" src="assets/skin/red.png" alt="red">
          <img class="img" src="assets/skin/green.png" alt="green">
        </div>
      </div>
      <div class="card c2">
        <div class="card-body">
          <h5 class="card-title"> Select Eyes</h5>
          <img class="img" src="assets/eyes/closed.png" alt="closed">
          <img class="img" src="assets/eyes/normal.png" alt="normal">
          <img class="img" src="assets/eyes/laughing.png" alt="laughing">
          <img class="img" src="assets/eyes/rolling.png" alt="rolling">
          <img class="img" src="assets/eyes/long.png" alt="long">
          <img class="img" src="assets/eyes/winking.png" alt="wink">
        </div>
      </div>
      <div class="card c3">
        <div class="card-body">
          <h5 class="card-title"> Select Mouth</h5>
          <img class="img" src="assets/mouth/open.png" alt="open">
          <img class="img" src="assets/mouth/smiling.png" alt="smiling">
          <img class="img" src="assets/mouth/straight.png" alt="straight">
          <img class="img" src="assets/mouth/sad.png" alt="sad">
          <img class="img" src="assets/mouth/teeth.png" alt="teeth">
        </div>
      </div>
    </div>
  </div>

  <div class="split right">
    <h2 class="head"> preview</h2>
    <div class="centered">
      <div id="preview">
        <img id="final" src="" alt="">
      </div>
    </div>
  </div>
  </div>


  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-/bQdsTh/da6pkI1MST/rWKFNjaCP5gBSY4sEBT38Q/9RBh9AH40zEOg7Hlq2THRZ" crossorigin="anonymous"></script>

</body>

</html>

CodePudding user response:

Try using forEach loop in JS it will make your task easier . Corrected JS code below

    let preview = document.getElementById('final')
    let img = document.getElementsByClassName('img')
    Array.from(img).forEach((i) => {
        i.addEventListener("click", () => {
            console.log(i.src);
            preview.src = i.src;
            
        });
    })

Note : I used Array.from method in js to convert returned nodes to an array of elements. For more info about this refer to MDN.

CodePudding user response:

Your img is not a single HTMLImageElement. It is a HTMLCollection, i.e. a list of images. Variables should be named appropriately to avoid, this kind of confusion.

To refer, to the clicked image inside the click event listener, declare the event parameter for the listener & use event.currentTarget inside.

// naming as imgList is better than img
let imgList = document.getElementsByClassName('img')
for ( var i = 1; i < imgList.length; i  ) {
   imgList[i].addEventListener("click",function(event){
       let clickedImg = event.currentTarget;
       preview.src = clickedImg.src;
   });
}
  • Related