Craig
Craig

Reputation: 31

Repeat a function on window resize in jQuery

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();
});

Upvotes: 3

Views: 10637

Answers (1)

Matt Howell
Matt Howell

Reputation: 15936

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();
});

Upvotes: 14

Related Questions