Solution for dynamically inserted elements with jQuery 1.9.1

188 views
Skip to first unread message

Savoul Pelister

unread,
May 28, 2014, 6:15:56 AM5/28/14
to threed...@googlegroups.com
I am not sue if this is a right way to do this, but it works or me.

This is what I have done. ( You no need to include 'jquery.event.drag.live-2.2.js' in your page )

Wrote a function like this calling the drag from jquery.event.drag


    $.fn.start_drag = function( ) {
       
        $( this ).drag( 'dragstart', function( ) {     
           
                // do something here
              
          }).drag( 'drag', function( ev, dd ) {
             
              $( this ).css({ top: dd.offsetY, left: dd.offsetX });
           
          });
    };

then called the function like this.

$('.drag').start_drag();

this will bind drag to all the div with class 'drag'

then while inserting the elements dynamically

$('.drag').unbind( 'drag' );  -  unbind drag from all the div with class 'drag'

then again call the function to bind drag.

$('.drag').start_drag();

Once again I dont know if this is correct, it will be nice if developer provide some solution.



ambrus.j...@gmail.com

unread,
Jun 2, 2014, 9:23:13 AM6/2/14
to threed...@googlegroups.com
Live binding actually uses a little different approach.
Your code basically binds an even to each of the ".drag" elements individually - creating unnecessary overhead via lots of event handlers.
Also, you need to do this binding manually every time you add a ".drag" component onto the page.

Live binding will instead use the fact that events in JavaScript bubble, thus binding only a single "drag" event to the container where all ".drag" elements reside.
This main container will then intercept any events passed to its descendants (i.e. our ".drag" elements). This function will check if the event comes from a ".drag" element first, then it will act upon it.

This is how the original "live" part of the drag&drop script works:

$( document ).on("drag",".drag",function( ev, dd ){

Savoul Pelister

unread,
Jun 4, 2014, 12:29:36 AM6/4/14
to threed...@googlegroups.com, ambrus.j...@gmail.com
I tried what you said first. it doesnt work with jQuery 1.9.1, which was my point. Your solution works on 1.7.2

try this
$('<div class="drag"/>').appendTo( '#container' ).start_drag();

in this case you no need to unbind or initiate drag again and again.
Reply all
Reply to author
Forward
0 new messages