Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to preview an uploaded image as the background image of a div?

I want to preview an uploaded image file in a div. I have done a bit of research and I have found this piece of code from this post, it is the code to preview an uploaded image file, but in an <img> tag:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

The associated HTML:

<body>
    <form id="form1" runat="server">
        <input type='file' onchange="readURL(this);" />
        <img id="blah" src="#" alt="your image" />
    </form>
</body>

Very cool. However, what I want is to display the uploaded image as the background image of a div, an example of which would be like this:

<div class="image" style="background-image:url('');"></div>

I know that, logically, I would have to replace

$('#blah').attr('src', e.target.result);

with something like

$('div.image').attr('style', e.target.result);.

But how to make the path of the image go into the value of the 'background-image' property?

And yes, do I need to link to the JQuery library for this?

Thank you.

like image 496
Hemkesh Molla Avatar asked May 01 '13 04:05

Hemkesh Molla


People also ask

Why is my Div background image not showing?

you have to change your path background-image: url('/ximages/websiteheader1. png') ; TO background-image: url('ximages/websiteheader1. png') ; actually, remove the first / from the path of the image.

Can you put a background image in a div?

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. Use it for aesthetic reasons, such as adding a textured background to your webpage.


1 Answers

You could use CSS shorthand just like in a CSS file. I recommend the following to avoid repeating and alignment issues:

<script type="text/javascript">
    function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

The change is the line like this

$('#objectID').css('background', 'transparent url('+e.target.result +') left top no-repeat');
like image 100
Ding Avatar answered Nov 14 '22 13:11

Ding