0

I want to make a list in which the user can add elements by clicking a button, change their colour by one click on the element and delete them with a long click on the element.

My code works fine for adding divs and changing their color:

$(document).ready(function(){
$('button').click(function(){
    var toAdd = $('input[name=shop-item]').val();
    if (toAdd == ''){
        return false;
    }
    else {
        $('#list').append('<div class="item item-red">' + toAdd + '</div>');
    });

$(document).on('click', '.item', function(){
    $(this).toggleClass('item-red');
    $(this).toggleClass('item-green');
});

But then I would like to be able to delete a single div with a long click. I found some examples like the following:

var timeoutId = 0;
$(document).on('mousedown', '.item', function(){
    timeoutId = setTimeout(function(){ $(this).remove() }, 500);
}).bind('mouseup mouseleave', function() {
    clearTimeout(timeoutId);
});

However, it doesn't work with 'this'. But if I use '.item' instead, obviously all the appended items are deleted.

Sam
  • 7,252
  • 16
  • 46
  • 65
peddersen
  • 13
  • 4

2 Answers2

0

Inside your setTimeout function, you are in a different scope. this has a different meaning. You could cache it instead:

$(document).on('mousedown', '.item', function(){
    var $this= $(this);
    timeoutId = setTimeout(function(){ $this.remove() }, 500);
})
Stryner
  • 7,288
  • 3
  • 18
  • 18
0

You can store the mousedown event timestamp every event has timestamp in its prototype

var mouseDownTimestamp = 0 $(document).on('mousedown',function(event){ mouseDownTimestamp = event.timeStamp;} ); $(document).on('mouseup',function(event){ //if the mouse up is after 499ms if(mouseDownTimestamp < event.timeStamp - 499){ //or $(event.target).remove(); //or $(event.target).closest('.class of the holder').remove(); $(selector).remove(); } });

D.Dobchev
  • 9
  • 1
  • 4