3

I've been trying to make this work for a little while now.

I thought the following code would work since I'm getting the value from the input and setting the background-image URL to said value.

Thanks!

The code inside of the head tag.

<script  type="text/javascript">

 function loadImg() {

  var imageUrl = $('#hostImage').attr('value')

  document.getElementById("upload-success-bg").style.backgroundImage=imageUrl

}

</script>

<style>

 #upload-success-bg {
 background-image: url();
 }

</style>

Input field code

<div class="status">

 <input class="image-url" type="text" id="hostImage" name="hostImage" required="true" 
 value="URL LOADS HERE">

</div>

Where I would like to the image to show

<div class="dropzone upload-success" id="upload-success-bg">
            <div class="info"><p>Drag image file here</p><p>Or click here to select image</p></div>
<input type="file" required="" class="input" accept="image/*"></div>
5
  • Possible duplicate of Javascript-Setting background image of a DIV via a function and function parameter Commented Feb 20, 2019 at 3:04
  • Two issues are if the code is within <head> element the element does not yet exist in the DOM, and the function does not appear to be called in the JavaScript at the question. In addition to CSS url() function not being used to set the value of background-image property. Commented Feb 20, 2019 at 3:09
  • 1
    What do you mean by "Where I would like to the image to show"? What is the purpose of the <input type="text"> element, and how is the.value of that element related to the <input type="file"> element and displaying an image? Commented Feb 20, 2019 at 3:20
  • @guest271314 The div "dropzone upload-success" is where a user drags an image file to upload. When a user uploads an image, the URL of the image becomes the value of <input type="text">. I want to take this url and make it the background of the dropzone div. Commented Feb 20, 2019 at 20:38
  • @machina The <input type="text"> element is not necessary. A File object does not have a URL property. A Blob URL or data URL can be created which points to the uploaded file. A Blob URLs lifetime is linked to the document which created the URL. A data URL represented a data:, MIME type, possibly <charset> <base64|text> encoding of the file. Commented Feb 20, 2019 at 20:41

3 Answers 3

5

If you wish to use an URL for backgound and background-color CSS properties you have to use the url() syntax even within javascript, so changing your code to the following should work:

document.getElementById("upload-success-bg").style.backgroundImage = "url(" + imageUrl + ")"
Sign up to request clarification or add additional context in comments.

Comments

2

In jquery, you can do it this way:

 function loadImg() {

  var imageUrl = $('#hostImage').attr('value')

  $("#upload-success-bg").css("background-image", "url(" + imageUrl + ")");

}

Comments

1

A File object does not have a URL property. A Blob URL or data URL can be created which points to the uploaded file. A Blob URLs lifetime is linked to the document which created the URL. A data URL string

data:[<mediatype>][;base64],<data>

can be opened at a different window or browser.

You can use FileReader to convert File object to a data URL and set the <input type="text"> value to the FileReader instance result.

const input = document.querySelector("#file");
const [label] = input.labels;
const upload = document.querySelector("#upload-success-bg");
const uploadURL = document.querySelector("#hostImage");
const reader = new FileReader();

reader.addEventListener("load", e => {
  const {result} = reader;
  upload.style.backgroundImage = `url(${result})`;
  hostImage.style.width = `calc(${result.length}px)`;
  hostImage.value = result;
});

input.addEventListener("change", e => {
  const [file] = input.files;
  console.log(file)
  if (file && /^image/.test(file.type)) {
    reader.readAsDataURL(file);
  }
});
#file {
  display: none;
}

label[for="file"] {
  white-space: pre;
}
<div class="dropzone upload-success" id="upload-success-bg">
  <label class="info" for="file">
    Drag image file here
    Or click here to select image
  </label>
  <input type="file" required="" id="file" class="input" accept="image/*"></div>
<div class="status">
  <input class="image-url" type="text" id="hostImage" name="hostImage" required="true" readonly="true" value="URL LOADS HERE">
</div>

3 Comments

I should've mentioned I'm using a script with Imgur API that when a user selects a file, it uploads to Imgur and returns the image URL.
@machina See stackoverflow.com/help/how-to-ask, stackoverflow.com/help/mcve. That does not affect the code at the answer. You can include the code which performs the asynchronous task within FileReader load event handler and set hostImage.value to the response text.
@machina (async() => { try { const request = await fetch("/path/to/server", {method:"POST", body:file}); const result = await request.text(); upload.style.backgroundImage = `url(${result})`; hostImage.style.width = `calc(${result.length}px)`; hostImage.value = result; } catch(e) {console.error(e)} })()

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.