Question: I have five img-elements, each with the class ".backgroundImage". The script below centers it. How can I tell my script to do it with every individual img without writing the script down 5 times?

```
function resize(){
    var imageWidth = $('.backgroundImage').width();
    var imageHeight = $('.backgroundImage').height();

    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    if(imageWidth>windowWidth){
        var newWidth = -(imageWidth - windowWidth)/2;
        $('.backgroundImage').css('margin-left', newWidth);
    };

    if(imageHeight>windowHeight){
        var newHeight = -(imageHeight - windowHeight)/2;
        $('.backgroundImage').css('margin-top', newHeight);
    };
};

```

The Script is triggered on document.ready and on window.resize

Answer: 
By passing in a variable

```
function resize(selector){
    var imageWidth = $(selector).width();
    var imageHeight = $(selector).height();

    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    if(imageWidth>windowWidth){
        var newWidth = -(imageWidth - windowWidth)/2;
        $(selector).css('margin-left', newWidth);
    };

    if(imageHeight>windowHeight){
        var newHeight = -(imageHeight - windowHeight)/2;
        $(selector).css('margin-top', newHeight);
    };
};

```

Now, that said, there is no reason to look up the selector so often:

```
function resize(selector){
    var $image = $(selector);
    var imageWidth = $image.width();
    var imageHeight = $image.height();

    var windowWidth = $(window).width();
    var windowHeight = $(window).height();

    if(imageWidth>windowWidth){
        var newWidth = -(imageWidth - windowWidth)/2;
        $image.css('margin-left', newWidth);
    };

    if(imageHeight>windowHeight){
        var newHeight = -(imageHeight - windowHeight)/2;
        $image.css('margin-top', newHeight);
    };
};

resize('.backgroundImage');

```
You can write a jQuery plugin as follow,

```
(function ($) {
   $.fn.centerImage = function () {
    var operations = {
        resize: function() {
            var windowWidth = $(window).width(),
                windowHeight = $(window).height(),
                imageWidth = this.width(),
                imageHeight = this.height();

            if (imageWidth > windowWidth) {
                var newWidth = -(imageWidth - windowWidth) / 2;
                this.css('margin-left', newWidth);
            }

            if (imageHeight > windowHeight) {
                var newHeight = -(imageHeight - windowHeight) / 2;
                this.css('margin-top', newHeight);
            }
        }
    };

    return this.each(function () {
        var ele = $(this);
        $(window).resize(function () {
            operations.resize.apply(ele, []);
        });
    });
 };
})(jQuery);

Then you can call this as,

$(document).ready(function(){
     $('.backgroundImage').centerImage ();
});

```

That's all