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)
4
  • When I press the "add" button, a file with file input is created and I choose my picture from there. Commented Feb 14, 2023 at 11:07
  • Maybe add event listener for "change" event? Commented Feb 14, 2023 at 11:07
  • @protob "change"? Commented Feb 14, 2023 at 11:09
  • Does this answer your question? Loading an image to a <img> from <input file> Commented Feb 14, 2023 at 11:15

1 Answer 1

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();
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.