Skip to content

Instantly share code, notes, and snippets.

@aliboy08
Created July 25, 2024 03:04
Show Gist options
  • Save aliboy08/7892c08aedf04757fa934f09df7cc1bb to your computer and use it in GitHub Desktop.
Save aliboy08/7892c08aedf04757fa934f09df7cc1bb to your computer and use it in GitHub Desktop.
Before & After Slider
export default class Before_After_Slider {
constructor(el){
this.el = el;
this.init();
}
init(){
this.before = this.el.querySelector('.before_image');
this.handle = this.el.querySelector('.handle');
this.pos = this.el.getBoundingClientRect();
this.initial_styles();
this.handle.addEventListener('mousedown',()=>this.activate());
document.body.addEventListener('mouseup',()=>this.deactivate());
this.handle.addEventListener('touchstart',()=>this.activate());
document.body.addEventListener('touchend',()=>this.deactivate());
window.addEventListener('resize', ()=>{
this.pos = this.el.getBoundingClientRect();
});
}
activate(){
this.handle.classList.add('active');
document.body.ba_slider = this;
document.body.addEventListener('mousemove', this.mouse_drag);
document.body.addEventListener('touchmove', this.touch_drag);
}
deactivate(){
this.handle.classList.remove('active');
document.body.removeEventListener('mousemove', this.mouse_drag);
document.body.removeEventListener('touchmove', this.touch_drag);
}
mouse_drag(e){
document.body.ba_slider.move(e.pageX);
}
touch_drag(e){
let x = e.changedTouches[0].pageX;
document.body.ba_slider.move(x);
}
move(pos_x){
pos_x -= this.pos.left;
let distance_x = Math.max(0,(Math.min(pos_x, this.el.offsetWidth)));
this.handle.style.left = distance_x + 'px';
this.before.style.width = distance_x + 'px';
}
initial_styles(){
let before_image = this.before.getElementsByTagName('img')[0];
before_image.style.width = this.pos.width + 'px';
before_image.style.height = this.pos.height + 'px';
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment