Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to upload image file from computer and set as div background image using jQuery?

The HTML code for image file input:

<input type="file" autocomplete="off" name="background-image" accept="image/*" />

The destination div block where I want to dynamically set the background image:

<div class="clock"></div>

The jQuery function I'm currently using for setting image file uploaded as div background image:

$(".background>div>input[type=file]").change(function () {
    var fileExtension = ['jpeg', 'jpg', 'png', 'gif', 'bmp'];
    if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
        alert("Only '.jpeg','.jpg', '.png', '.gif', '.bmp' formats are allowed.");
    }
    else {
        $(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');
    }
});

The issue is that the background-image is not being set. This may possibly be because when I checked with browser inspector, the file upload is not containing file url. Note: The background-color of .clock is set to white initially.Also I'd not like to use a server since my intention is to keep it as client side only application.

like image 778
RBk Avatar asked Jul 11 '15 05:07

RBk


People also ask

Can a div have a background image?

Say you want to put an image or two on a webpage. One way is to use the background-image CSS property. This property applies one or more background images to an element, like a <div> , as the documentation explains.

How do you add a background to a div in HTML?

To add background color in HTML, use the CSS background-color property. Set it to the color name or code you want and place it inside a style attribute. Then add this style attribute to an HTML element, like a table, heading, div, or span tag.


1 Answers

This may solve your problem

JS FIDDLE

HTML

<input type='file' id='getval' name="background-image" /><br/><br/>
<div id='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);
function readURL(){
   var file = document.getElementById("getval").files[0];
   var reader = new FileReader();
   reader.onloadend = function(){
      document.getElementById('clock').style.backgroundImage = "url(" + reader.result + ")";        
   }
   if(file){
      reader.readAsDataURL(file);
    }else{
    }
}
like image 122
Malik Naik Avatar answered Sep 18 '22 11:09

Malik Naik