I inherited a wordpress site and am trying my best to incorporate some features from a new designer. One of them is a drag out panel where the user clicks on a little icon and drags left and right. I have never done a dragging type effect before and sort of stumbled my way into writing a little script that I feel like should work, but doesn't. Here is my script. The user is supposed to drag an icon which behind the scenes is adding to the margin-left attribute of it's parent div. This is supposed to mean the user sees the effect of dragging the div into view. At the start the div is pushed off the screen my a margin-left of -1100px.:
var dragging = false;
var start;
$(document).on('mousedown', function(e){
if ($(e.target).is('.dragme')) {
dragging = true;
start = 0 - e.pageX;
}
});
$(document).on('mouseup', function(){
dragging = false;
start = 0;
});
const offset = $('.dragme').offset().left;
$(document).on('mousemove', function(e){
if (!dragging) {
return;
}
else {
let move = start + e.pageX;
let margin = parseInt($('#section4 .overlay').css('margin-left').replace(/[^-\d\.]/g, ''));
$('#section4 .overlay').css('margin-left', (margin + move) + 'px');
}
});
and my dragme image css:
.dragme {
cursor: move;
position: absolute;
right: 0;
top: 50%;
z-index: 20000;
transform: translateY(-50%);
}
Right now my code is allowing the user to click on the image and drag but you can't see the effect taking place, so you won't see the div reposition until they let go. Also, the mouseup event isn't firing so after the user drags and moves the mouse again the div gets all crazy because dragging is still true. Any ideas what I am doing wrong? Also, please don't recommend I use jQuery draggable or some other library. I don't want to add any more bloat to this site.
I'm not sure where is mistake in your code, but anyway use my Codepen.
$(function() {
var $win = $(window),
$overlay = $('.overlay'),
dragging = false,
start = 0,
defaultMargin = +$overlay.css('margin-left').replace(/[^-\d\.]/g, '');
$win.on('mousedown', function(e) {
if ($(e.target).is('.dragme')) {
dragging = true;
start = e.pageX;
}
});
$win.on('mouseup', function(e) {
dragging = false;
start = e.pageX;
defaultMargin = +$overlay.css('margin-left').replace(/[^-\d\.]/g, '');
});
$win.on('mousemove', function(e) {
if(!dragging) return false;
var move = e.pageX - start;
$overlay.css({marginLeft: defaultMargin + move + 'px'});
});
});
.overlay {
position: absolute;
width: 90%;
height: 100px;
margin-left: -200px;
background-color: green;
}
.dragme {
width: 20px;
height: 20px;
background-color: yellow;
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="overlay">
<div class="dragme"></div>
</div>