iwrestledthebeartwice
iwrestledthebeartwice

Reputation: 734

How to convert this javascript to function to work on button click?

I'm trying to upload image to Imgur using javascript and I found the following code online. It uploads the image to Imgur once the file is changed. I want to upload it to imgur only when the user clicks on upload button.

How do I fix this? Here is my code:

const file = document.getElementById("file")
const img = document.getElementById("img")
const url = document.getElementById("url")

file.addEventListener("change", ev => {
  const formdata = new FormData()
  formdata.append("image", ev.target.files[0])
  
  fetch("https://api.imgur.com/3/image/", {
    method: "post",
    headers: {
      Authorization: "Client-ID client-id-goes-here"
    },
    body: formdata
  }).then(data => data.json()).then(data => {
    img.src = data.data.link
    url.innerText = data.data.link
  })
})
<img src="" id="img" height="200px">
<br />
<input type="file" id="file">
<br />
<strong>
   <p id="url"></p>
</strong>

I want to convert the file.addEventListener to something like upload() and use this HTML button <button onclick="upload()">upload</button> to upload it to Imgur.

Any help would be appreciated. Thanks :)

Upvotes: 0

Views: 143

Answers (4)

NeNaD
NeNaD

Reputation: 20334

You can refactor your code like this:

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

  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Imgur API Image Uploader</title>
  </head>

  <body>
    <img src="" id="img" height="200px">
    <br />
    <input type="file" id="file">
    <br />
    <strong>
      <p id="url"></p>
    </strong>
    <button onclick="upload()">
      UPLOAD
    </button>

    <script>
      const file = document.getElementById("file")
      const img = document.getElementById("img")
      const url = document.getElementById("url")
      let currentFile;

      file.addEventListener("change", ev => {
        currentFile = ev.target.files[0];
      })

      function upload() {
        const formdata = new FormData()
        formdata.append("image", currentFile)
        fetch("https://api.imgur.com/3/image/", {
          method: "post",
          headers: {
            Authorization: "Client-ID client-id-goes-here"
          },
          body: formdata
        }).then(data => data.json()).then(data => {
          img.src = data.data.link
          url.innerText = data.data.link
        })
      }
    </script>

  </body>

</html>

Upvotes: 1

Real Quick
Real Quick

Reputation: 2800

You attach the eventListener to a button instead of the file. And change the event from change to click.

const file = document.getElementById("file")
const img = document.getElementById("img")
const url = document.getElementById("url")
document.getElementById("upload-button").addEventListener("click", ev => {
    const formdata = new FormData()

    formdata.append("image", file.files[0])
    fetch("https://api.imgur.com/3/image/", {
        method: "post",
        headers: {
            Authorization: "Client-ID client-id-goes-here"
        },
        body: formdata
    }).then(data => data.json()).then(data => {
      console.log("uploaded");
        img.src = data.data.link
        url.innerText = data.data.link
    })
})
<img src="" id="img" height="200px">
<br />
<input type="file" id="file">
<br />
<strong>
    <p id="url"></p>
</strong>
<button id="upload-button">UPLOAD</button>

Upvotes: 2

Kunal Mukherjee
Kunal Mukherjee

Reputation: 5853

Just listen to the click handler of the button and perform your XHR call inside it.

window.onload = function() {
  document.querySelector('#btnUploadFile').addEventListener('click', async function(event) {
    try {
      const file = document.getElementById("file")
      const img = document.getElementById("img")
      const url = document.getElementById("url")

      const formdata = new FormData();
      formdata.append("image", file.files[0]);

      const imgurResponse = await fetch("https://api.imgur.com/3/image/", {
        method: "post",
        headers: {
          Authorization: "Client-ID client-id-goes-here"
        },
        body: formdata
      });

      const data = await imgurResponse.json();
      img.src = data.link
      url.innerText = data.link;
    } catch (err) {
      console.error(err);
    }
  });
};
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Imgur API Image Uploader</title>
</head>

<body>
  <img src="" id="img" height="200px">
  <br />
  <input type="file" id="file">
  <br />
  <strong>
        <p id="url"></p>
    </strong>
  <button id="btnUploadFile">Upload</button>
</body>

</html>

Upvotes: 2

Omri Attiya
Omri Attiya

Reputation: 4037

Just export the change event function to a function upload and replace the ev.target with the file element object

const file = document.getElementById("file");
const img = document.getElementById("img");
const url = document.getElementById("url");

function upload() {
  const formdata = new FormData()
  formdata.append("image", file.files[0])
  fetch("https://api.imgur.com/3/image/", {
    method: "post",
    headers: {
      Authorization: "Client-ID client-id-goes-here"
    },
    body: formdata
  }).then(data => data.json()).then(data => {
    img.src = data.data.link
    url.innerText = data.data.link
  })
})
<img src="" id="img" height="200px">
<br />
<input type="file" id="file">
<br />
<p id="url"></p>
<button click="upload()">upload</button>

Upvotes: 1

Related Questions