user6725906 user6725906 - 3 months ago 5
CSS Question

Comparing width and height of uploaded picture

I have a file input (picture) and I want to set its

div
's
class
depending on what is bigger: its
width
or its
height
.

My code is not working (only the last
if
statement), the
div
's class never changes, regardless to the uploaded image.

This is my HTML:

<div class="row">
<div class="col-md-12">
<div id="blah" class="profilePic">
<img src="profilkep.jpg" />
</div>
</div>
</div>

<br>

<div class="row">
<div class="col-md-12">
<input type="file" onchange="previewFile()">
</div>
</div>


And this is my JavaScript:

function previewFile(){
var preview = document.querySelector('img'); //selects the query named img
var file = document.querySelector('input[type=file]').files[0]; //sames as here
var reader = new FileReader();

reader.onloadend = function () {
preview.src = reader.result;
}

if (file) {
reader.readAsDataURL(file); //reads the data as a URL
} else {
preview.src = "";
}

if (file.width < file.height) {
document.getElementById("blah").setAttribute("class", "blahblah");
} else {
document.getElementById("blah").setAttribute("class", "profilePic");
}
}

Answer

The problem is that you have two same IDs blah. All ids need to be unique. file.width and file.height are always undefined. Here is the fix:

 <div class="row">
  <div class="col-md-12">
    <div id="blah">
      <img id="profileImage" src="profilkep.jpg" />
    </div>
  </div>
</div>

<br>

<div class="row">
  <div class="col-md-12">
    <input type="file" onchange="previewFile()">
  </div>
</div>
  <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <script type="text/javascript">
    function previewFile(){
        var preview = document.querySelector('img'); //selects the query named img
        var file    = document.querySelector('input[type=file]').files[0]; //sames as here
        var reader  = new FileReader();

        reader.onloadend = function () {
          preview.src = reader.result;
          var imageWidth = $('#profileImage').width();
          var imageHeight = $('#profileImage').height();
          if (imageWidth < imageHeight) {
          console.log('width < height');
          document.getElementById("blah").setAttribute("class", "blahblah");
        } else {
          console.log('width > height');
          document.getElementById("blah").setAttribute("class", "profilePic");
        }
        }

        if (file) {
          reader.readAsDataURL(file); //reads the data as a URL
        } else {
          preview.src = "";
        }

      }
    </script>    
Comments