-1

I have an event for click-and-hold on a dynamic element

    var timeoutId = 0;
    $(document).on('mousedown', '.createbtn', function(){
        timeoutId = setTimeout(showNewInfoCreateDlg, 1000);
    }).on('mouseup mouseleave', '.createbtn', function() {
        clearTimeout(timeoutId);
    });

and the function is "showNewInfoCreateDlg" I need to know what is the id of the element that was clicked-and-held

    function showNewInfoCreateDlg(){
      alert($(this).attr('id'));
    }

The function alerts "undefined"

Here is the jsfiddle for my problem:

JsFiddle

user1137313
  • 2,390
  • 9
  • 44
  • 91

1 Answers1

1

Explicitly bind it to the function:

var timeoutId = 0;
$(document).on('mousedown', '.createbtn', function(){
    timeoutId = setTimeout(showNewInfoCreateDlg.bind(this), 1000);
}).on('mouseup mouseleave', '.createbtn', function() {
    clearTimeout(timeoutId);
});

To clarify: The bind() function will, well, bind the value of its first argument to the this variable inside showNewInfoCreateDlg. This is called explicit binding.

AVAVT
  • 7,058
  • 2
  • 21
  • 44