Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Get SRC of Javascript image

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

i tried ;

image.src = URL.createObjectURL(image)

>Solution :

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();
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading