I have over 400 simple divs and two buttons to move them up and down. Everythig works but I want to keep mouse button pressed and move the items by much greater speed then using single click, one by one. Is it possible?
$(document).on('click', '.item', function() {
$('.marked').removeClass('marked');
$(this).addClass('marked');
});
$('#mpup').click(function() {
if ($('.marked').index() == 0) {
return false;
}
var i = $('.marked').index() - 1;
$('.marked').insertBefore($('.item').eq(i));
});
$('#mpdown').click(function() {
var i = $('.marked').index() + 1;
$('.marked').insertAfter($('.item').eq(i));
});
.marked {
background: red;
}
.item {
cursor: pointer
}
.mpbtn {
background: teal;
color: white;
cursor: pointer;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='itemwrap'>
<div class='item marked'>323</div>
<div class='item'>525</div>
<div class='item'>727</div>
</div><br><br>
<div class='mpbtn' id='mpup'>UP</div><br>
<div class='mpbtn' id='mpdown'>DOWN</div>
To achieve this you need to use the mousedown and mouseup events. On mouse down you can use a setInterval() to repeatedly move the element in the required direction. You can also (optionally) use a setTimeout() to add a delay before the repeated action starts to stop accidental duplicate movements. In the mouseup you simply need to then clear those timers.
Also note that you can genericise the code by using a data attribute to store the direction in which the relevant button should move the selected option.
Try this:
$(document).on('click', '.item', function() {
$('.marked').removeClass('marked');
$(this).addClass('marked');
});
var mouseTimer, mouseInterval;
$('.mpbtn').on({
mousedown: function() {
var dir = parseInt($(this).data('dir'), 10);
move(dir);
mouseTimer = setTimeout(function() {
mouseInterval = setInterval(function() {
move(dir)
}, 100);
}, 250);
},
mouseup: function() {
clearTimeout(mouseTimer);
clearInterval(mouseInterval);
}
});
function move(dir) {
if (dir < 0 && $('.marked').index() == 0)
return;
var i = $('.marked').index() + dir;
$('.marked')[dir < 0 ? 'insertBefore' : 'insertAfter']($('.item').eq(i));
}
// only to populate demo:
var html = '';
for (var i = 1; i <= 10; i++) {
html += '<div class="item">' + i + '</div>';
}
$('#itemwrap').html(html).find('div:first').addClass('marked');
.marked {
background: red;
}
.item {
cursor: pointer
}
.mpbtn {
background: teal;
color: white;
cursor: pointer;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='itemwrap'></div><br><br>
<div class='mpbtn' id='mpup' data-dir="-1">UP</div><br>
<div class='mpbtn' id='mpdown' data-dir="1">DOWN</div>
Working fiddle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With