Well I'm kind of new with jQuery and javascript and I have written 'some' code for a image slider but it is enormous. I am convinced it can be shorter, but I don't know how. Could somebody show me how it sould be done so I can learn from it ? Thanks in advance :D
PS I don't want to look lazy, I really want to get better in Javascript and Jquery
Here is my code
jQuery(document).ready(function(){
//Variables for image slider
var imgWrapper = $('.carousel-wrapper'),
img = $('.carousel-box'),
imgWidth = $('.carousel-box').width(),
imgLength = $('.carousel-box').length, // 4
currentMargin = imgWrapper.css('margin-left').replace('px',''), //0px
responsiveLength = 3,
maxMargin = -((imgLength - responsiveLength) * imgWidth),
minMargin = 0; //0px
$(window).resize(function(){
if ($(window).width() <= 1080) {
responsiveLength = 2;
maxMargin = -((imgLength - responsiveLength) * imgWidth);
} else if ($(window).width() <= 700) {
responsiveLength = 1;
maxMargin = -((imgLength - responsiveLength) * imgWidth);
} else {
responsiveLength = 3;
maxMargin = -((imgLength - responsiveLength) * imgWidth);
}
});
//Transition animation on click
$('.portbutton').click(function(){
//Get the direction
var dir = $(this).data('dir');
if (dir === 'next' && currentMargin != maxMargin) {
currentMargin -= imgWidth;
imgWrapper.animate({marginLeft: currentMargin},300);
} else if (dir === 'next' && currentMargin === maxMargin){
currentMargin = minMargin;
imgWrapper.animate({marginLeft: currentMargin},300);
} else if (dir === 'prev' && currentMargin != minMargin){
currentMargin += imgWidth;
imgWrapper.animate({marginLeft: currentMargin},300);
} else {
currentMargin = maxMargin;
imgWrapper.animate({marginLeft: currentMargin},300);
}
});
});