Reputation: 767
I have written some jQuery functions to resize images, keeping their aspect ratio on pageload, and window resize. These functions work great, but I built them specifically for one scenario. Now, another similar scenario has arisen in which I must do nearly the same functionality, only with iFrames. In the interest of becoming a better coder, and not adding extra code how can I concisely and efficiently re-use these functions for iFrames across the site, as well as the $('.com-background > img')
scenario?
Here is the jQuery:
function imageCalc() {
$imgWidth = $('.com-background > img').width();
$imgHeight = $('.com-background > img').height();
$imgAspectRatio = $imgHeight / $imgWidth;
$('.com-background > img').css('margin-left', '-10px' );
}
function setImageDims() {
$('.com-background > img').css('height', function( calcHeight ) { return $imgAspectRatio * $('#main-content').width(); });
$('.com-background > img').css('width', function( calcWidth ) { return $('#main-content').width() + 20; });
}
function imageResize() {
$('.com-background > img').css('width', function( resizeWidth ) { return $("body").width() });
$('.com-background > img').css('height', function( resizeHeight ) { return $imgAspectRatio * $('.com-background > img').width(); });
}
Upvotes: 0
Views: 55
Reputation: 1384
What @nnnnnn from the comments means is :
Update the functions to take the selector as an argument instead of hard-coding it?
Turn this :
function imageCalc() {
$imgWidth = $('.com-background > img').width();
$imgHeight = $('.com-background > img').height();
$imgAspectRatio = $imgHeight / $imgWidth;
$('.com-background > img').css('margin-left', '-10px' );
}
To this :
//where selector is your string query
function imageCalc(selector) {
$imgWidth = $(selector).width();
$imgHeight = $(selector).height();
$imgAspectRatio = $imgHeight / $imgWidth;
$(selector).css('margin-left', '-10px' );
}
The above changes would make your functions generic, in the sense that you can do the same to other DOM objects as long as you specify what to change via the selector argument. To do the same thing you're doing right now, you have to call imageCalc('.com-background > img');
, and so on.
And by this,
Also, unrelated to your question, cache your jQuery objects, don't keep re-selecting the same elements within the same function
he means :
//where selector is your string query
function imageCalc(selector) {
var obj=$(selector);
$imgWidth = obj.width();
$imgHeight = obj.height();
$imgAspectRatio = $imgHeight / $imgWidth;
obj.css('margin-left', '-10px' );
}
What this does is cache your object, which means you just locate it one time, and reuse that same object. It makes a difference in the performance, because everytime you use $(selector)
, you're re-searching the DOM tree to find that one element, which does take time.
Upvotes: 3