0

I want a user to select a background image from his local drive using javascript

He can set an image (id='imageID') as shown below

html

java script

image_file.onchange = function() {
var files = this.files;
var file = URL.createObjectURL(files[0]);
imageID.src = file;}

But if I change the 'target' in to the backgroundImage of a div by changing the last line to the one shown below, it does not work...

document.getElementById('divID').style.backgroundImage.src= file;
  • Does this answer your question? [how to change the background image of div using javascript?](https://stackoverflow.com/questions/21496905/how-to-change-the-background-image-of-div-using-javascript) Also see [Change css background-Image using javascript](https://stackoverflow.com/questions/52510749/change-css-background-image-using-javascript) and [How to dynamically set background image url in CSS using Javascript](https://stackoverflow.com/questions/54778142/how-to-dynamically-set-background-image-url-in-css-using-javascript). – showdev Sep 03 '21 at 04:15

1 Answers1

0

Try using a url() function in CSS to set style.backgroundImage (which is CSS property not an Image object. It is also a good idea to revoke object URLs that are no longer being used - they attach a blob object to the document and take up memory.

"use strict";
let oldURL = null;
function catchDrag(event) {
    event.dataTransfer.dropEffect = "copy"
    event.preventDefault();
}
document.body.addEventListener("dragenter", catchDrag);
document.body.addEventListener("dragover",  catchDrag);
document.body.addEventListener("drop", function( event) {
    event.preventDefault();
    event.stopPropagation();
    const file = event.dataTransfer.files[0];
    let newURL = URL.createObjectURL( file);
    if( oldURL) {
        URL.revokeObjectURL(oldURL);
    }
    oldURL = newURL;
    document.getElementById("divID")
        .style.backgroundImage = `url("${newURL}")`;

});
#divID {
   width: 400px;
   height: 300px;
   border: medium solid grey;
   background-size: contain;
}
Drag and drop an image onto this page to set the background of this box:

<div id="divID"></div>
traktor
  • 17,588
  • 4
  • 32
  • 53