How to evalute code in the chain or pretend callback function?
I dynamically add an image on my page :
<div class="simple_overlay" id="overlay">
<img src="" />
</div>
<script type="text/javascript">
$(function() {
$("a[rel]").overlay({
var source = 开发者_Python百科this.getTrigger().attr('href');
this.getOverlay().find("img").attr({'src': source});
});
});
</script>
Now, I need to get width of the new image and calculate margin-left
corresponding to it. Native jQuery Tools methods doesn't work, because when overlay is loading, image hasn't yet loaded and container #overlay
width is 0.
Is there any option to emulate callback on this chain, so i can use width()
right after attr()
has evaluated?
Use the images load
event (not to be confused with window.load
), like this:
$("a[rel]").overlay({
var source = this.getTrigger().attr('href');
this.getOverlay().find("img").one('load', function() {
//run your code here, the image is loaded and is "this"
}).each(function() {
if (this.complete) $(this).load(); //trigger load, handles from cache cases
}).attr({'src': source});
});
This uses .one()
to run your code only once. The load
event fires when that image is loaded...but this doesn't always fire when loading it from cache (depending on browser), which is what the .each()
is for. If the browser loaded it from cache and fired the event...that's ok too, the .one()
handles that, code still runs once in every case :)
精彩评论