Search code examples
javascriptjqueryappendlong-click

jQuery/Javascript - Edit and delete appended elements by different click times


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.


Solution

  • 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);
    })