A
A
Andrew Kolomiets2021-06-17 14:02:52
JavaScript
Andrew Kolomiets, 2021-06-17 14:02:52

How can this code be optimized?

There is a piece of code

$('.buy7').on('click', function(){
    $('.bought7').fadeIn(600);
    $('.tovar7').val($('.h27').text());
    $(this).fadeOut();
});
$('.otmena7').on('click', function(){
    $('.bought7, this').fadeOut(600);
    $('.buy7').show();
});

$('.buy8').on('click', function(){
    $('.bought8').fadeIn(600);
    $('.tovar8').val($('.h28').text());
    $(this).fadeOut();
});
$('.otmena8').on('click', function(){
    $('.bought8, this').fadeOut(600);
    $('.buy8').show();
});


There are 8 such buttons on the site, how can you optimize to a single template for all 8?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-06-17
@Coolam

Elementary after all cycle:

for (let i = 1; i<= 8; i++) {
  $('.buy' + i).on('click', function(){
      $('.bought' + i).fadeIn(600);
      $('.tovar' + i).val($('.h2' + i).text());
      $(this).fadeOut();
  });
  $('.otmena' + i).on('click', function(){
      $('.bought' + i + ', this').fadeOut(600);
      $('.buy' + i).show();
  });
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question