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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With