Mohammad Rashid Mohammad Rashid - 6 months ago 22
HTML Question

jQuery photoResize function isn't working

I'm new to jQuery and i'm still in the process of learning HTML and CSS. I wanted to have a responsive image on the homepage of my website that scaled itself with the user's browser window. I found this at github: https://github.com/gutierrezalex/photo-resize.git
but i think i might be using it wrong, since i can't get it to work for me.
Here's my html:

<head>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>

<reference path="jquery-1.5.1.min.js" />
<script src="jquery-photo-resize.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
$("img").photoResize()
});
</script>
</head>


and here's the jquery-photo-resize.js file:

function photoResize($) {
"use strict";
$.fn.photoResize = function (options) {

var element = $(this),
defaults = {
bottomSpacing: 10
};

function updatePhotoHeight() {
var o = options,
photoHeight = $(window).height();

$(element).attr('height', photoHeight - o.bottomSpacing);
}

$(element).load(function () {
updatePhotoHeight();

$(window).bind('resize', function () {
updatePhotoHeight();
});
});

options = $.extend(defaults, options);

};
}


Like i said, i'm a novice, so please let me know what i'm doing wrong, and how i can achieve my desired effect.

Answer

You don't need jquery for this. Just set a class name and then in your style sheet use a width. If you only set a width it'll auto size the height to maintain the aspect ratio. Same goes for setting the height only. If you set both your aspect ratio may be off. The width can be a percentage of the current element. You could also use vw (view port width). Also calc is super helpful.

{ width:75%}

Update:

.cropper {
  width: 75px;
  height: 75px;
  overflow: hidden;
  position: relative;
}

.cropped {
  width: 100px;
  position: absolute;
  left: -12.5px;
  top: -12.5px;
}
<div class="cropper">
  <img class="cropped" src="https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/SIPI_Jelly_Beans_4.1.07.tiff/lossy-page1-256px-SIPI_Jelly_Beans_4.1.07.tiff.jpg"/>
</div>