My comparison function allows users to slide left and right to view before and after images, functioning well thanks to the code I found on CodePen.
However, I have one issue - I want text to appear on the left and right sides of the image, disappearing as the slider approaches and reappearing when it moves away. The same functionality should apply to both sides.
Does anyone have any suggestions on how I can achieve this? You can view the code here.
Thank you for your help!
$(document).ready(function () {
$('.ba-slider').each(function () {
var cur = $(this);
// Adjust the slider
var width = cur.width() + 'px';
cur.find('.resize img').css('width', width);
// Bind dragging events
drags(cur.find('.handle'), cur.find('.resize'), cur);
});
});
// Update sliders on resize
$(window).resize(function () {
$('.ba-slider').each(function () {
var cur = $(this);
var width = cur.width() + 'px';
cur.find('.resize img').css('width', width);
});
});
function drags(dragElement, resizeElement, container) {
// Dragging event on mousedown
dragElement.on('mousedown touchstart', function (e) {
dragElement.addClass('draggable');
resizeElement.addClass('resizable');
// Determine mouse or touch event
var startX = (e.pageX) ? e.pageX : e.originalEvent.touches[0].pageX;
// Get initial position
var dragWidth = dragElement.outerWidth(),
posX = dragElement.offset().left + dragWidth - startX,
containerOffset = container.offset().left,
containerWidth = container.outerWidth();
// Set limits
minLeft = containerOffset + 10;
maxLeft = containerOffset + containerWidth - dragWidth - 10;
// Calculate drag distance
dragElement.parents().on("mousemove touchmove", function (e) {
var moveX = (e.pageX) ? e.pageX : e.originalEvent.touches[0].pageX;
leftValue = moveX + posX - dragWidth;
// Prevent going off limits
if (leftValue < minLeft) {
leftValue = minLeft;
} else if (leftValue > maxLeft) {
leftValue = maxLeft;
}
widthValue = (leftValue + dragWidth / 2 - containerOffset) * 100 / containerWidth + '%';
// Set new values for the slider and handle
$('.draggable').css('left', widthValue).on('mouseup touchend touchcancel', function () {
$(this).removeClass('draggable');
resizeElement.removeClass('resizable');
});
$('.resizable').css('width', widthValue);
}).on('mouseup touchend touchcancel', function () {
dragElement.removeClass('draggable');
resizeElement.removeClass('resizable');
});
e.preventDefault();
}).on('mouseup touchend touchcancel', function (e) {
dragElement.removeClass('draggable');
resizeElement.removeClass('resizable');
});
}
Cheers!