Home > Mobile >  JS,HTML Form I want to make preview and preview image size pix
JS,HTML Form I want to make preview and preview image size pix

Time:12-13

I make a preview function with HTML Form and JS But This function has a problem. I upload image and that size has too big or too small So, I want to make a function about preview image size pix.

This is My code HTML

<tr>
                    <td><input type="file" name="fileName" accept="image/*" onchange="setThumbnail(event);"></td>
                    <td><div id = "image_container"  style:width 100px; ></div></td>
                </tr>\

JS

function setThumbnail(event) {
    var reader = new FileReader();

    reader.onload = function(event){
        var img = document.createElement("img");
        img.setAttribute("src",event.target.result);
        document.querySelector("div#image_container").appendChild(img);
       
    };
    
    reader.readAsDataURL(event.target.files[0]);
}

So i was tried to give the style on div like width 100px height 100px but it dosen't work...

PlZ help me

CodePudding user response:

Your main problem is here: <div id = "image_container" style:width 100px;></div>, this is not the right way to add inline-style to a html tag.Style attribute is like other html tag's attribute and you have to follow the rule <div attr-name="attr-value"/> like this: <div id = "image_container" style="width 100px;height:100px;"></div>. BTW, you should set width,height of your image 100% in order to fit the image inside it's container. You can do it like this: (I don't use inline-style in the below snippet)

function setThumbnail(event) {
    var reader = new FileReader();
    reader.onload = function(event){
    const imageContainer = document.querySelector("div#image_container");
    var img = document.createElement("img");
    img.setAttribute("src",event.target.result);
    image_container.innerHTML = '';
    imageContainer.appendChild(img);
  };
  
  reader.readAsDataURL(event.target.files[0]);
}
.thumbnail{
  width:100px;
  height:100px;
}

.thumbnail img{
  width:100%;
  height:100%;
}
<table>
  <tr>
    <td>
      <input
        type="file"
        name="fileName"
        accept="image/*"
        onchange="setThumbnail(event)"
      />
    </td>
    <td>
      <div id="image_container" ></div>
    </td>
  </tr>
</table>

  • Related