setinterval - Self clearing an interval inside jquery.each() -
i need position/resize image javascript after has loaded. maintain aspect ratio intact have know image's width/height. can utilize .load
event, fires way late, making repositioning visible. instead utilize next technique.
var interval = setinterval(function(){ if ($('img').height()) { //this means have got height. //code uses $('img').height(). clearinterval(interval); } },10);
this makes sure code executed when have width/height info image, , before it's loaded.
now, however, need bunch of images (specifically in jquery plugin) , problem seems first clearinterval
invocation clears intervals, leaving first img
untouched.
i have tried saving interval id in $(this)
jquery object both property ($(this).interval = setinterval( ...
, info $(this).data("interval", setinterval( ...
.
i tried saving id in variable first above , assigning $(this).data("interval",interval)
after closing parenthesis of setinterval
call.
what right way every interval clears , itself?
full listing of code follows
(function($){ $.fn.extend({ centerinparent: function(options) { var defaults = { mode: "fill", //fill or fit (not implemented) padding: 100 } var options = $.extend(defaults, options); homecoming this.each(function() { var o = options; $t = $(this) $p = $t.parent(); var interval = setinterval(function(){ $t.css({position:"absolute", width:"", height:""}) if ($t.height()){ parentratio = $p.innerwidth()/$p.innerheight(); thisratio = $t.innerwidth()/$t.innerheight(); if (thisratio > parentratio) var newwidth = $p.innerwidth() - o.padding; else var newwidth = ($p.innerheight() - o.padding)*thisratio; var newheight = newwidth/thisratio $t.css({ width: newwidth, height:newheight, margintop: ($p.innerheight() - newheight)/2, marginleft: ($p.innerwidth() - newwidth)/2 }) clearinterval($t.data("interval")); } }, 10) $t.data("interval",interval) }); } }); })(jquery);
off top of head:
shouldn't $t
, $p
not global variables? i.e. declared as
var $t = $(this), $p = t.parent();
the method load image , wait 10 msec compute size unsafe in opinion: yield different results in different browsers
better preload images , compute size before displaying them :
var img = new image(); img.src = 'http://your-image-url'; $(img).load(function(){ // here, deal img.width , img.height // , display });
jquery setinterval
No comments:
Post a Comment