javascript - Passing two different arguments to function -
i have written jquery functions, , realized needed reuse code situation. refactored code take selector arguement, can utilize case 1, , case 2. however, when execute functions in document.ready
weird results.
$( document ).ready(function() { imagecalc('.com-background > img'); setimagedims('.com-background > img', '#main-content'); imagecalc('.blog-entry-content iframe'); setimagedims('.blog-entry-content iframe', '#content'); });
it should noted, these selectors no show on same page. also, when run 1 instance of imagecalc()
, setimagedims()
these functions work fine. here functions in question..
function imagecalc(selector) { var obj=$(selector); $imgwidth = obj.width(); $imgheight = obj.height(); $imgaspectratio = $imgheight / $imgwidth; // $(selector).css('margin-left', function( calcmargin ) { homecoming parseint($('.main-content').css('padding')) * -1 + "px"; }); prepare ie obj.css('margin-left', '-10px' ); } function setimagedims(selector, content_area) { var container = $(content_area); $(selector).css('height', function() { homecoming $imgaspectratio * container.width(); }); $(selector).css('width', function() { homecoming container.width() + 20; }); }
in summary, code works fine, when have each function called 1 time in document.ready
need utilize code 2 scenarios, how can this?
add var
in front end of $imgwidth
, $imgheight
, , $imgaspectratio
variables. without var
, they're beingness declared @ global scope, , hence accidentally getting shared across both calls function.
update: noticed $imgaspectratio
beingness used both functions. perhaps can create homecoming value first function, can passed sec function.
to elaborate... should theoretically work, although i'm not able test since don't have corresponding html:
function imagecalc(selector) { var obj=$(selector); var $imgwidth = obj.width(); var $imgheight = obj.height(); var $imgaspectratio = $imgheight / $imgwidth; // $(selector).css('margin-left', function( calcmargin ) { homecoming parseint($('.main-content').css('padding')) * -1 + "px"; }); prepare ie obj.css('margin-left', '-10px' ); homecoming $imgaspectratio; } function setimagedims(selector, content_area, $imgaspectratio) { var container = $(content_area); $(selector).css('height', function() { homecoming $imgaspectratio * container.width(); }); $(selector).css('width', function() { homecoming container.width() + 20; }); } $( document ).ready(function() { var ratio1 = imagecalc('.com-background > img'); setimagedims('.com-background > img', '#main-content', ratio1); var ratio2 = imagecalc('.blog-entry-content iframe'); setimagedims('.blog-entry-content iframe', '#content', ratio2); });
javascript jquery
No comments:
Post a Comment