How to take an image input and display it in the background-image?

Asked

Viewed 186 times

3

I have an input field that should receive an image, when receiving it I should add it as background-image from a div. I used Filereader to get the Base64 from the image. It works fine, but CSS cannot load the image. Since they are user inputs I can’t get a URL.

I’ve tried using:

document.getElementById('div').style.backgoundImage = "url('${imageData}')";

.div{
        position: absolute;
        background-image: url('${imageData}');
    }
  • Why put it in the CSS if Javascript has already changed the background? In addition to what CSS is interpreted when opening the page, after that you cannot change its source code.

  • Javascript did not change the background, those were examples of failed attempts.

2 answers

2

There are two errors in the code:

  1. Letter is missing r in .backgoundImage. Seria .backgroundImage.
  2. The interpolation of the string with placeholder ${} will only work between the signs of crass:
    document.getElementById('div').style.backgroundImage = `url(${imageData})`;

Take an example:

let imageData = "https://www.cleverfiles.com/howto/wp-content/uploads/2016/08/mini.jpg";
document.getElementById('div').style.backgroundImage = `url(${imageData})`;
<div id="div" style="width: 500px; height: 300px; border: 1px solid #000"></div>

  • I thank you for correcting the mistakes, I wrote very quickly and I did not pay attention to that. Anyway the code I’m trying to use is all right.

  • As I said in the question itself the image is an input, I will not have its url.

1


Yes you can do this with the api Filereader.

It is worth giving a reading also in the section of browser support

function onSelectImage(event) {
	// se usuário não selecionou nenhum imagem não faça nada
	if (!event.target.files.length) return;

	// aqui pegaremos a primeira imagem da lista: FileList
	var selectedFile = event.target.files[0];

	// FileReader https://developer.mozilla.org/en-US/docs/Web/API/FileReader/readAsDataURL
	var reader = new FileReader();

	// assim que terminar de ler a imagem
	// jogá-la como plano de fundo da div#image-area
	reader.onload = function(event) {
		document.querySelector('#image-area').style.background = "url('" + event.target.result + "') no-repeat 0 0";
	};

	// Informa ao reader para ler a image como base64
	reader.readAsDataURL(selectedFile);
}
#image-area {
  width: 200px;
  height: 200px;
  margin-top: 10px;
}
<input type="file" id="file_input" onchange="onSelectImage(event)"/>
<div id="image-area"></div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.