How to dynamically set background image url in CSS using Javascript

javascript get background image url
how to change background image automatically using javascript
how to set background image dynamically in html
javascript change background image on click
css dynamic background-image: url
javascript background image
how to set background image in canvas using javascript
javascript remove background-image

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>

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 + ")"

HTML DOM Style backgroundImage Property, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java� The backgroundImage property sets or returns the background image of an element. Tip: In addition to the background-image you should also specify a background-color. The background-color will be used if the image is unavailable.

In jquery, you can do it this way:

 function loadImg() {

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

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

}

Background images in CSS, How to set dynamically images on the background. To show how the color of the background of a page or the image may be changed dynamically, a JavaScript function alters the of this CSS attribute. For images, you can use images / url (10. jpg) and replace 10 by 20, 50, 60, 80. image: Sets the background image for an element: repeat: Sets how a background image will be repeated: attachment: Sets whether a background image is fixed or scrolls with the page: position: Sets the starting position of a background image: size: Sets the size of a background image: origin: Sets the background positioning area: clip: Sets the

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>

Changing dynamically images or the background of a web page, Setting or Replacing Dynamically Images. How to change an image, or the background of the page, once the page is displayed by the The JavaScript code. Changing your website styles dynamically is taking over the web! In this post I will explain how to do some simple yet effective CSS tricks using jQuery.

Dynamic multiple CSS backgrounds via JS - JavaScript, Dynamic multiple CSS backgrounds via JS $(this).parent().css({'background- image':'url('+ background +')'});. or in plain JS (preferred): it needs to be inline; Setting this background the CSS way in Javascript outputs this:. In this tutorial, we are going to learn about how to set a background-image in the react app using inline styles and external css. This tutorial assumes that you already created a new react project using create-react-app. Setting image using inline styles. Example:

backgroundImage style property JavaScript, Specifies or returns the image to use as the background of the object. CSS page for this property: background-image url(URI) width: 300px; height: 200px; overflow: scroll; } </style> </head> <body> <div class="example"> Some content . Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java and XML.

How to Set CSS background-image Property Using jQuery, To set the CSS background-image property of an element using the jQuery if you've an image URL stored in a JavaScript variable then in CSS() method you� For full-width/full-height you can use percentages or potentially "background-size:cover" (haven't checked) and then call a CSS animation to change the images dynamically. Or 2. you can add multiple images to a background in your CSS separated by commas, apply background-size:cover and again use CSS animations to change the background.

Comments
  • Possible duplicate of Javascript-Setting background image of a DIV via a function and function parameter
  • 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.
  • 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?
  • @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.
  • @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.
  • 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)} })()