3

I wrote a function that resizes and positions fixed-position images. I want to repeat the function "imgControl" on window resize in jQuery. I'm sure that there is some super easy way to do this, but my searching has been fruitless so far. I may just not know the right search terms to use. Any help would be greatly appreciated!

The whole thing works perfectly if I simply copy the function into the resize event, but that seems inelegant and unnecessary. It seems like there ought to be a way to just call up the function again.

Here's my code:

$(window).load(function imgControl() {
    $('div.lb_img img').each(function () {
        var lb_img_id = '#' + $(this).attr('id');
        /* image size */
        var max_height = $(window).height() - 50;
        var max_width = $(window).width() - 50;
        $(function() { $(lb_img_id).aeImageResize({width:max_width, height:max_height}); });
        /* image position */
        var img_y = ($(this).attr('height') + 14) * -0.5;
        var img_x = ($(this).attr('width') + 14) * -0.5;
        $(this).css('margin-top', img_y).css('margin-left', img_x);
    });
}); 
$(window).resize(function() {
    imgControl();
});
Craig
  • 31
  • 1
  • 1
  • 2
  • possible duplicate of [jQuery resize function doesn't work on page load](http://stackoverflow.com/questions/2597152/jquery-resize-function-doesnt-work-on-page-load) – davidcondrey Jun 09 '15 at 09:02

1 Answers1

14

Define your function in a way that it's callable from wherever you need it. Like so:

var imgControl = function() {
    $('div.lb_img img').each(function () {
        ... // etc
    });
};

$(document).ready(function () {
    imgControl();
});

$(window).resize(function() {
    imgControl();
});
Matt Howell
  • 15,750
  • 7
  • 49
  • 56
  • I know, it's like a race sometimes. :) – Matt Howell Mar 16 '11 at 04:45
  • Thanks bigmattyh! And also, thanks CtrlDot, for making the effort. That worked perfectly, and now I know something that I really ought to have known already. – Craig Mar 16 '11 at 04:49
  • 4
    btw: there is no need for the anonymous functions, you can use simply `$(imgControl);` and `$(window).resize(imgControl);`. – diego nunes Apr 29 '13 at 23:17