Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Dynamically scale down images based on their original height and width
CHANGE IMAGE SIZE RELATIVE TO ITSELF AND NOT A PARENT
FORGOT THE WEIRD BOUNDING BOX ISSUE WITH TRANSFORM: SCALE();
THOSE WHO DON'T UNDERSTAND JQUERY/JS SCROLL DOWN TO LINE 32
function shrinkImage(idOrClass, className, percentShrinkage){
'use strict';
$(idOrClass+className).each(function(){
var shrunkenWidth=this.naturalWidth;
var shrunkenHeight=this.naturalHeight;
$(this).height(shrunkenWidth*percentShrinkage);
$(this).height(shrunkenHeight*percentShrinkage);
});
};
FOR THOSE THAT UNDERSTAND JQUERY/JS
1. className parameter will identify which elements in the DOM you want to change. This parameter must be in quotes as it is a string.
2. The second parameter is a multple by which you want to scale up or scale down your images. (eg if you want to shrink by half, use .5). this parameter should NOT be wrapped in quotes
3. Wrap it in whatever event handler you see fit.
4. See my personal example below:
$(document).ready(function(){
'use strict';
shrinkImage(".","half",.5);
});
FOR THOSE THAT DO NOT UNDERSTAND JQUERY/JS THIS IS STILL REALLY EASY TO USE JUST FOLLOW THESE INSTRUCTIONS
1. Copy the code block on lines 4-12 exactly AND PASTE INTO A JS FILE THAT YOU WILL REFERENCE ON YOUR WEB PAGE.
2. Below that copy the code on lines 20-23 below it.
3. The only code you have to customize is where it says, "." "half" and .5
example: shrinkImage("periodOrHashtag","domNameHereInQuotes",percentShrinkageHere)
5. The first parameter will only accept a period "." or hashtag "#" to identify whether you are looking for a class or Id
4. The second one must be the class or id name (for a group of images) or an id(for a single image and it MUST BE IN QUOTES.
5. The third is the multiple by which you want to shrink or grow the images
6. If you want different images to have different scale percentages then copy code on lines 20-23 and change the className and percentage shrink for each.
7.5. A comma separates all of these.
If you have questions SEND ME A MESSAGE AND I WILL WALK YOU THROUGH. I've been where you are and want to help.
SEE WHAT YOUR CODE SHOULD LOOK LIKE BELOW:
function shrinkImage(idOrClass, className, percentShrinkage){
'use strict';
$(idOrClass+className).each(function(){
var shrunkenWidth=this.naturalWidth;
var shrunkenHeight=this.naturalHeight;
$(this).height(shrunkenWidth*percentShrinkage);
$(this).height(shrunkenHeight*percentShrinkage);
});
};
$(document).ready(function(){
'use strict';
shrinkImage(".","half",.5);
});
$(document).ready(function(){
'use strict';
shrinkImage("#","anyID",.9);
});
$(document).ready(function(){
'use strict';
shrinkImage(".","anyClass",2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.