Skip to content

Commit

Permalink
dragging js code
Browse files Browse the repository at this point in the history
  • Loading branch information
Ayush Gaggar committed Oct 2, 2024
1 parent 1602e45 commit 56c5522
Showing 1 changed file with 39 additions and 9 deletions.
48 changes: 39 additions & 9 deletions static/js/slider.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,49 @@
// Get the slider element and add event listeners for 'input' and 'change'
const imgSlider = document.getElementById("img-slider");
imgSlider.addEventListener("input", handleSliderChange);
imgSlider.addEventListener("change", handleSliderChange);

// Function to handle slider changes
export function handleSliderChange(e) {
const sliderPos = e.target.value;

// Function to handle slider movement
function handleSliderChange(sliderPos) {
// Update the width of the foreground image
document.querySelector('.foreground-img').style.width = `${sliderPos}%`;

// Update the position of the slider button
document.querySelector('.img-slider-button').style.left = `calc(${sliderPos}% - 18px)`;
}

// Variables to track mouse movement
let isDragging = false;

// Handle the mouse down event (when the user clicks on the slider button)
document.querySelector('.img-slider-button').addEventListener('mousedown', (e) => {
isDragging = true; // Start dragging
document.body.style.cursor = 'grabbing'; // Change cursor to indicate dragging
});

// Handle the mouse move event (when the user drags the slider button)
document.addEventListener('mousemove', (e) => {
if (isDragging) {
// Get the bounding box of the slider track (or container)
const slider = document.getElementById('img-slider');
const rect = slider.getBoundingClientRect();

// Calculate the new slider position as a percentage based on mouse position
const offsetX = e.clientX - rect.left;
let sliderPos = (offsetX / rect.width) * 100;

// Clamp the value between 0% and 100% to prevent overflow
sliderPos = Math.max(0, Math.min(100, sliderPos));

// Update the slider's value and visuals
slider.value = sliderPos;
handleSliderChange(sliderPos);
}
});

// Handle the mouse up event (when the user releases the mouse button)
document.addEventListener('mouseup', () => {
if (isDragging) {
isDragging = false; // Stop dragging
document.body.style.cursor = 'default'; // Reset the cursor
}
});

// export function initComparisons() {
// var x, i;
// /* Find all elements with an "overlay" class: */
Expand Down

0 comments on commit 56c5522

Please sign in to comment.