MS Wachasunder
MS Wachasunder

Reputation: 65

Auto adjust background image using css

I have the following code for uploading background image.

<input type='file' onchange="readURL(this);" />

The script I'm using is:

function readURL(input) {
            if (input.files && input.files[0]) {
                var reader = new FileReader();

                reader.onload = function (e) {

                    $('#myframe')

                    .css({
                    background:'url('+e.target.result +') left top no-repeat',
                    background-size:'400px 400px'

                    });

                };

               reader.readAsDataURL(input.files[0]);//To display images uncomment this
            }
        }

There is a problem.Above code works if I remove background-size. I want to reduce the size and resolution of the image I'm uploading. Here$('#myframe') is div id of the the area, where I want to upload. Also, let me know how do I pass multiple properties to .css() function. I tried the following code for the same, but no effect:

.css(background:transparent url('+e.target.result +') left top no-repeat,background-size:200px 300px);

Upvotes: 0

Views: 134

Answers (2)

waqar mirza
waqar mirza

Reputation: 555

I have created a jsfiddle http://jsfiddle.net/kHqLE/2/

The output from e.target.result is not an image object, its a raw string.

Upvotes: 1

GillesC
GillesC

Reputation: 10874

Your problem is that background is a super property and it reset background-size, place background-size after background.

So in your case you want:

$('#myframe')
    .css('background', 'transparent url('+e.target.result +') left top no-repeat')
    .css('background-size', '200px 300px');

See this post background overwrites background-size

And css to pass multiple properties you simply pass in an object. See documentation http://api.jquery.com/css/

Upvotes: 1

Related Questions