I was trying to make a div which could be moved to any position like drag and drop function. I used the following approach:
var songs = {};
songs.clickedM = 0;
$(".song-progress .current-position")[0].addEventListener("mousedown", function(down2) {
songs.clickedM = 1;
var intpos2 = down2.clientX;
$(".song-progress .current-position")[0].addEventListener( "mousemove", function(Dmove2) {
if(songs.clickedM == 1) {
if (Dmove2.clientX <= $(".song-progress").offset().left) {
$(".song-progress .current-position")[0].style.left = "0px";
}
else if( Dmove2.clientX >= ($(".song-progress").outerWidth() + $(".song-progress").offset().left)) {
$(".song-progress .current-position")[0].style.left = ( $(".song-progress").outerWidth() - 14) + "px";
}
else {
$(".song-progress .current-position")[0].style.left = (Dmove2.clientX - $(".song-progress").offset().left ) + "px";
}
}
});
});
$("body")[0].addEventListener("mouseup", function() {
songs.clickedM = 0;
});
.container {
padding: 100px;
width: 700px;
height: 500px;
background-color: lightgray;
}
.song-progress {
position: absolute;
top: 84px;
right: 15px;
height: 5px;
width: calc(100% - 135px);
background-color: white;
}
.current-progress{
position: absolute;
left: 0;
width: 0px;
height: 5px;
background-color: #bbb;
}
.current-time {
position: absolute;
bottom: 5px;
font-size: 10px;
left: 0;
font-family: "Times New Roman"
}
.total-time {
position: absolute;
bottom: 5px;
right: 0;
font-size: 10px;
font-family: "Times New Roman"
}
.current-position {
height: 9px;
width: 15px;
background-color: #00cdff;
position: absolute;
top: -2.5px;
left: 1px;
cursor: pointer;
border-radius: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="song-progress">
<div class="current-time">1:21</div>
<div class="total-time">5:37</div>
<div class="current-progress"></div>
<div class="current-position"></div>
</div>
</div>
I noticed that songs.clickedM
never becomes 0
, even when mouse key is released. My guess is that the mousemove
event listener is a function which is acting like a function closure. And when the mouse moves for the first time after first click it accesses a copy of songs.clickedM
not the original. It is unaware of the fact that the original variable songs.clickedM
has actually been changed to 0
.
How do I make the value of
songs.clickedM
0
formousemove
event listener when the key is not pressed?