JQuery + AngularJS: mousedown event is being called multiple times


I have a single page application in angular.

I cannot use jQuery draggable method so I wrote one myself –

 // here I am setting the drag event to a div
var enableDrag = function(id){

var handleMousedown =function (e){
    window.my_dragging = {};
    my_dragging.pageX0 = e.pageX;
    my_dragging.pageY0 = e.pageY;
    my_dragging.elem = this;
    my_dragging.offset0 = $(this).offset();
    var isDragAction=false;
    function handle_dragging(e){
        var left = my_dragging.offset0.left + (e.pageX - my_dragging.pageX0);
        var top = my_dragging.offset0.top + (e.pageY - my_dragging.pageY0);
            .offset({top: top, left: left});
    function handle_mouseup(e){
            .off('mousemove', handle_dragging)
            .off('mouseup', handle_mouseup);
            console.log("drag was done!!");
            console.log("click was done!!");

        .on('mouseup', handle_mouseup)
        .on('mousemove', handle_dragging);

And in my method I am calling this like this:

   //set off the last mousedwon to the div
   //set the mousedwon to the div

I need to call it each time the method is being called instead of just one time because of how my angular app is working.

The dragging works fine.

The problem is that each time the method is being called – a new event is being added in addition to the previous events..


First method is being called – dragging will print to the console:

"drag was done!!"

Second method is being called, on a single drag:

"drag was done!!"
"drag was done!!"

In time method is being called, on a single drag:

"drag was done!!"
"drag was done!!"
"drag was done!!"

what is accumulating the events or causing this multiple prints?


Try ensuring the event is set only once by removing it before setting it, rather than doing it separately. Not sure this is the problem because I haven’t tested it in your example.

var enableDrag = function(id) {
  $('#'+id).off('mousedown').on('mousedown', handleMousedown);

Answered By – Jared Insel

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published