K
K
Kusmich2015-11-16 12:45:39
JavaScript
Kusmich, 2015-11-16 12:45:39

How to do code refactoring?

There is a code in which only class names and variables with a counter change. But he repeats himself three times. Can it be reduced to one beautiful function?

the code:

var itt = 0;
var itt_2 = 0;
var itt_3 = 0;

$('.first_div > img').each(function(i, elem) {
  itt++;
  console.log(itt);
  var lefted = -20 * itt;
  $('.first_div > img').eq(itt).css({
    'left': lefted + 'px'
  });
  //console.log(lefted)  
});

$('.sekond_div > img').each(function(i, elem) {
  itt_2++;
  console.log(itt_2);
  var lefted = -20 * itt_2;
  $('.sekond_div > img').eq(itt_2).css({
    'left': lefted + 'px'
  });
  //console.log(lefted)  
});



$('.sird_div > img').each(function(i, elem) {
  itt_3++;
  console.log(itt_3);
  var lefted = -20 * itt_3;
  $('.sird_div > img').eq(itt_3).css({
    'left': lefted + 'px'
  });
  //console.log(lefted)  
});								

});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deodatuss, 2015-11-16
@Kusmich

function myIterator(){
   var itt=0;
   return(function(i, elem) {
  itt++;
  console.log(itt);
  var lefted = -20 * itt;
  $(this).eq(itt).css({
    'left': lefted + 'px'
  });
})
}
$('.first_div > img').each(myIterator());

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question