Katerpiler
Katerpiler

Reputation: 119

How to loop within the .each() function inside the UL tag

I'm trying to make this dynamic. So I have 9 images and I want to change the width(px) increasing by 10px and when reached fifth image it should be decreasing to the original size by 10px. So far I got to increase all the way.

$( ".org-collections li img" ).each(function( index ) {
  var index = index+"9";
  var calc = 150+parseInt(index);

  if(calc == 199){

  } 
  $(this).css("max-width",calc+"px");
});

Here is the demo.

Example: enter image description here

Upvotes: 1

Views: 67

Answers (1)

Robin Zigmond
Robin Zigmond

Reputation: 18249

This is basically the calculation you want to do. I've been playing in JSFiddle to get the "best-looking" values of the constants involved, feel free to alter them to suit:

(Note that the maximum value, which I've got as 150 here, doesn't work too well if you make it much higher - I assume it's to do with the intrinsic dimensions of the image, it doesn't seem to want to get taller than a particular value.)

$( ".org-collections li img" ).each(function( index ) {
  var calc = 150 - 9*Math.abs(4 - index);
  $(this).css("max-width",calc+"px");
});

Also, the value of 4 works because it's the middle value, assuming you've got exactly 9 images (as you do here). If you might have a variable number n, then as long as it's odd then you can replace 4 by (n - 1) / 2

Upvotes: 2

Related Questions