Search code examples
javascriptjqueryhtmlcssjquery-callback

JQuery callback function doesn't work


I'm trying to use callback function of the following type:

$('elem').attr(
'attr',
function(i, val){
    return i*10 + 'px';
   }
);

to place images one on top of another.

My HTML includes five images only.

CSS:

img {
position: absolute;
width: 100px;
height: auto;
}

JQuery:

$('img').attr(
'top',
function(i, val){
    alert(50 + i*110 + 'px');
    return 50 + i*(110) + 'px';
  }
);

Alerts in the page: 50px...160px...270px...380px...490px But images still stuck in one place. Can you find error here?


Solution

  • What you're doing is setting an HTML property, not a CSS property. You image becomes <img top=50px></img>, which to the browser means nothing. Use the jquery .css() function to manipulate css:

    $('img').css(
        'top',
        function(i, val){
            return 50 + i*(110) + 'px';
        }
    );
    

    Eg. http://jsfiddle.net/M6SZE/