I have the following jquery code which i want to add the styling to the image uploaded. Does any know how i can add style after the src in the jquery.
<div id="container">
<input id="fileUpload" type="file" />
<br />
<div id="image-container"> </div>
</div>
$("#fileUpload").on('change', function() {
if (typeof(FileReader) == "undefined") {
alert("Your browser doesn't support HTML5, Please upgrade your browser");
} else {
var container = $("#image-container");
//remove all previous selected files
container.empty();
//create instance of FileReader
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
// I want to add the syle here
"src": e.target.result
}).appendTo(container);
}
reader.readAsDataURL($(this)[0].files[0]);
}
});
2 Answers 2
// I want to add the syle here
You can simply add the style like:
"style": "width:100px;height:100px",
$("#fileUpload").on('change', function() {
if (typeof(FileReader) == "undefined") {
alert("Your browser doesn't support HTML5, Please upgrade your browser");
} else {
var container = $("#image-container");
//remove all previous selected files
container.empty();
//create instance of FileReader
var reader = new FileReader();
reader.onload = function(e) {
$("<img />", {
"style": "width:100px;height:100px",
"src": e.target.result
}).appendTo(container);
}
reader.readAsDataURL($(this)[0].files[0]);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
<input id="fileUpload" type="file" />
<br />
<div id="image-container"> </div>
</div>
answered Jul 3, 2017 at 17:24
gaetanoM
42.1k6 gold badges45 silver badges63 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
This is one way to do it.
let imageStyle = "width:150px";
$("#image-container").append("<img id='theImg' src='" + e.target.result +"' style='"+ imageStyle +"'/>");
This can also be done as
var img = $('<img>');
img.attr('src', e.target.result);
img.attr('style', imageStyle);
img.appendTo('#image-container');
answered Jul 3, 2017 at 17:24
Hassan Imam
22.6k6 gold badges45 silver badges53 bronze badges
Comments
default