2
\$\begingroup\$

I've been doing this image slider section, I've been working on this code for quite a time, the code is perfectly working but I want to improve it.

I tried for hours and couldn't find a way. Maybe because I'm too in my code that I can't see other better options.

Can you guys suggest me a better way to improve my code?

let $roller = $('#management_roller .manage-roller');
let rollerChild = $roller.children();
let childNumber = rollerChild.length;
let number = 0;

const getTranslteX = () => {
  const matrix = $roller.css('transform').split(',');
  return Math.abs(parseInt(matrix[12] || matrix[4] || 0));
}

const howBig = () => {
  const windowW = window.innerWidth;
  if(windowW <= 576) {
    return 1;
  } else if(windowW <= 768) {
    return 2;
  } else if(windowW <= 1200) {
    return 3;
  } else {
    return 4;
  }
} 


const setX = (n) => {
  $roller.css({'transform' : 'translateX(-' + n +'px)'});
}



$('#roller_links a').click(function(e) {
  e.preventDefault();

  $('#roller_links a').removeClass('active');
  const id = $(this).attr('id');
  const rollerP = $roller.parent();

  $(this).addClass('active');
  rollerP.hide();
  $roller = $('#' + id + '_roller .manage-roller');
  rollerChild = $roller.children();
  number = 0;
  $roller.parent().show();
  setX(number * $(rollerChild[number]).outerWidth());
});



$('#roller-n').click(function() {
  if(childNumber - howBig() === number) return;
  number++;
  setX(getTranslteX() + 
$(rollerChild[number]).outerWidth());
});

 $('#roller-p').click(function() {
  if(number === 0) return;
  number--;
  setX(Math.abs(getTranslteX() - 
$(rollerChild[number]).outerWidth()));
});


$(window).on('resize', function() {
  if(childNumber - howBig() < number) number = 
 childNumber - howBig();
  setX(number * $(rollerChild[number]).outerWidth());
 });
\$\endgroup\$
  • \$\begingroup\$ Are you able to add the basic HTML elements that accompany this JS? If so, please edit the post and add it. \$\endgroup\$ – Sᴀᴍ Onᴇᴌᴀ Mar 22 '18 at 5:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.