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


the html code image file input:

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

the destination div block want dynamically set background image:

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

the jquery function i'm using setting image file uploaded 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 allowed.");     }     else {         $(".clock").css("background-image",'url("' + $(".background>div>input[type=file]").val() + '")');     } }); 

the issue background-image not being set. may possibly because when checked browser inspector, file upload not containing file url. note: background-color of .clock set white initially.also i'd not use server since intention keep client side application.

this may solve 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{     } } 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -