How To Upload Image File From Computer And Set As Div Background Image Using Jquery?
The HTML code for image file input:   The destination div block where I want to dynamically s
Solution 1:
This may solve your problem
HTML
<inputtype='file'id='getval'name="background-image" /><br/><br/><divid='clock'></div>CSS
#clock{
   background-image:url('');
   background-size:cover;
   background-position: center;
   height: 250px; width: 250px;
   border: 1px solid #bbb;
}
PURE JAVASCRIPT
document.getElementById('getval').addEventListener('change', readURL, true);
functionreadURL(){
   var file = document.getElementById("getval").files[0];
   var reader = newFileReader();
   reader.onloadend = function(){
      document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";        
   }
   if(file){
      reader.readAsDataURL(file);
    }else{
    }
}
Solution 2:
It's small way to do this without using FileReader.
http://jsfiddle.net/PuneetChawla/vqn7r0nj/
HTML
<inputtype='file'id='getval'name="background-image"onchange="readURL(event)" /><br/><br/><divid='clock'></div>CSS
#clock{
           background-image:url('');
           background-size:cover;
           background-position: center;
           height: 250px; width: 250px;
           border: 1px solid #bbb;
            }
JavaScript
function readURL(event){
         var getImagePath = URL.createObjectURL(event.target.files[0]);
         $('#clock').css('background-image', 'url(' + getImagePath + ')');
        }
Explanation - The URL.createObjectURL() static method creates a DOMString containing an URL representing the object given in parameter.
Solution 3:
var loadFile = function(event) {
    var output = document.getElementById('output');
    output.style.backgroundImage= "url("+URL.createObjectURL(event.target.files[0])+")";
  };<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><html><body><inputtype="file"accept="image/*"onchange="loadFile(event)"><divstyle="width: 500px;height: 500px;"id="output"></div></body></html>
Post a Comment for "How To Upload Image File From Computer And Set As Div Background Image Using Jquery?"