PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 27, 2022

[FIXED] How to apply url url uploaded as css background?

 October 27, 2022     javascript, jquery     No comments   

Issue

I need to grab the browse image upload url and apply it as a background cover to a div, and this is what I've tried but i don't get the background image:

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $("#top_img").css("background-image", e.target.result);
      $("#top_img").css("background-size", "cover");
    }
    reader.readAsDataURL(input.files[0]);
  }
}
$("#upload").change(function() {
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input id="upload" class="form-control" type="file" id="formFile">

<div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>


Solution

Problem is that you need to include url() when setting the background-image, so use:

$("#top_img").css("background-image", `url(${e.target.result})`);

Demo

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
    console.log("T",e.target.result)
      $("#top_img").css("background-image", `url(${e.target.result})`);
      $("#top_img").css("background-size", "cover");
    }
    reader.readAsDataURL(input.files[0]);
  }
}
$("#upload").change(function() {
  readURL(this);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="upload" class="form-control" type="file" id="formFile">


<div id="top_img" style="height: 484px; width: 1080px; position: relative; top:0; left: 0;"></div>



Answered By - Carsten Løvbo Andersen
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing