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: 
Look into $.each. Something like:

```
$('.backgroundImage').each(function(index, value){
  var width = $(value).width();
  var height = $(value).height();  // Value is each individual img element

  // do your resizing on each value as necessary
})

```
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');

```