0

I am creating an image gallery in javascript and I wrote some functions for it. When I click the "add" button, a window opens to select a file and a "<img>" tag is created in my relevant container, but how do I automatically put the src of the SELECTED image in my img tag?

my codes;

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Roboto+Mono:ital@1&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="style.css">
    <title>Gallery</title>
</head>

<body>
    <div class="container">
        <h1>Gallery</h1>
        <button id="addButton">Add</button>
        <div id="containerImage" class="container-image"></div>
    </div>

    <script src="app.js"></script>
</body>

</html>
let addButton = document.querySelector("#addButton");
let imageContainer = document.querySelector("#containerImage");


addButton.addEventListener('click', function () {
    let input = document.createElement('input');
    input.type = "file";
    input.click();
});

addButton.addEventListener('click',function(){
    let image = document.createElement('img');
    imageContainer.appendChild(image);
    image.className="resim";
    
});

Im new to javascript and I'm trying to do small small projects

i tried ;

image.src = URL.createObjectURL(image)

1 Answers1

1
addButton.addEventListener('click', function () {
  let input = document.createElement('input');
  input.type = "file";
  input.addEventListener('change', function () {
    let image = document.createElement('img');
    image.className = "resim";
    image.src = URL.createObjectURL(input.files[0]);
    imageContainer.appendChild(image);
  });
  input.click();
});
protob
  • 3,317
  • 1
  • 8
  • 19