1

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.

Link

 <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

1

// 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>

Sign up to request clarification or add additional context in comments.

Comments

1

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');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.