Tibby
Tibby

Reputation: 344

Change DIV background to jpg in input file

When I upload a file it updates the IMG SRC. I would like to update the background of #gal01 with the image I upload from the input file. Here is the code:

HTML:

<img id="mlogo" src="#" alt=" " />
<br>
<div id="gal01">
 <input type="file" name="fileToUpload" accept="image/jpeg" class="fileInput" id="fileToUpload" onchange="readURL(this);" />
</div>

I have a Div with a transaparent input file.

JavaScript:

try {function readURL(input) {
 if (input.files && input.files[0]) {
  var reader = new FileReader();
   reader.onload = function (e) {
    $('#mlogo')
    .attr('src', e.target.result)
    .width(95)
    .height(95);
    };
   reader.readAsDataURL(input.files[0]);
  }
 }
} catch (error) { throw error; }

CSS:

img {
 width:                 95px;
 height:                95px;
}

#gal01 {
 width:                 95px;
 height:                95px;
 overflow:              hidden;
 position:              relative;
 cursor:                pointer;
 background-color:      #F00;
 background:            url("http://www.dari.com/images/galimg.png") no-repeat scroll 0px 0px rgba(0, 0, 0, 0);
}

.fileInput {
    cursor: pointer;
    height: 100%;
    position:absolute;
    top: 0;
    right: 0;
    font-size:50px;
    opacity: 0;
    -moz-opacity: 0;
    filter:progid:DXImageTransform.Microsoft.Alpha(opacity=0)
}

Thank you for the help!

JSFiddle

Upvotes: 1

Views: 259

Answers (2)

Ivan Jovović
Ivan Jovović

Reputation: 5298

Just find $('#gal01') and set it's css background property to e.target.result:

    $('#gal01')
.css('background', 'url('+e.target.result+') no-repeat scroll 0px 0px rgba(0, 0, 0, 0)')
.css( 'background-size', 'cover');

inside reader.onload = function (e) {...

Working fiddle: http://jsfiddle.net/se0kssLf/2/

Upvotes: 2

Sonaryr
Sonaryr

Reputation: 1122

made you a new version for your fiddle:

http://jsfiddle.net/se0kssLf/3/

you need to set the background of your div:

$('#gal01').attr('style', 'background: url('+e.target.result+');background-size: 95px 95px;'); 

Upvotes: 2

Related Questions