Currently, I am in the process of creating a custom horizontal slider for my client's personalized gallery. The gallery comprises elements displayed as a no-wrap, multi-window-width block, designed to change its margin-left
when the slider arrows are clicked.
The increment/decrement value for the margin-left needs to be adjustable through a variable
, ensuring that it remains functional regardless of the current responsive CSS document loaded.
I attempted to develop a script where the width of the photo-container
div is obtained, saved as a variable, and then utilized as the right-hand argument in the animate()
function. However, this approach did not yield the desired outcome. In fact, it failed to work entirely, often resulting in an invalid tween error displayed in the console.
Here is my script:
$(document).ready(function() {
var imageWidthToSlice = $(".gallery-element-wrapper").css("width");
imageWidth = imageWidthToSlice.slice(0, -2);
defaultMargin = $(".gallery-element-wrapper:first").css("margin-left").slice(0, -2);
numberOfElements = $(".gallery-element-wrapper").length;
totalWidth = imageWidth * numberOfElements;
$(".gallery-arrow").click(function() {
if ( $(".gallery-element-wrapper:first").css("margin-left").slice(0, -2) != defaultMargin ) {
$(".gallery-element-wrapper:first").animate({
marginLeft: "+="imageWidth;
},500);
}
else {
console.log("This is the first image, can't slide left more.");
}
});
});
Visual overview on the subject: https://i.sstatic.net/THZ6d.jpg
Also available on JSFiddle: