Matthias
Matthias

Reputation: 45

Resize an image using JavaScript / jQuery

I know this question has been answered many times. However, my code does not seem to work despite I literally got it from the internet. I probably do something wrong, but what exactly I could not figure out.

I put the following JS code inside the HTML <head> tag :

$(document).ready(function() {
  var imwidth = $('#jspp').width(); 
  var imheight = $('#jspp').height(); 
  if (imwidth < imheight) {
   $('#jspp').width(100);
  } else {
   $('#jspp').height(100);
  }	 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
  <div>
    <img id="jspp" src="https://placehold.it/300x300">
  </div>
</body>

Does somebody have an idea of what could be wrong?

Thanks in advance!

Upvotes: 0

Views: 38

Answers (1)

Shiladitya
Shiladitya

Reputation: 12161

Here you go with a solution https://jsfiddle.net/027q85w8/

$(document).ready(function() {
  var imwidth = $('#jspp').width(); 
  var imheight = $('#jspp').height(); 

  if (imwidth < imheight) {
    $('#jspp').css('width', '100px');
  } else {
    $('#jspp').css('height', '100px');
  }   
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <img id="jspp" src="http://via.placeholder.com/350x150">
</div>

Two things were wrong in your code.

  • Missing ) at the end of document.ready
  • Assigning of 100px in width & height.

Hope this will help you.

Upvotes: 1

Related Questions