javascript - jQuery draggable creates duplicate sub items -
i'm using jquery ui draggable function. full code more complicated created simple test scenario troubleshoot bug here: fiddle
there 2 sections "top" , "content". there yellow button in "top" section draggable.
when drag yellow button @ top , drop gray "content" area, show in gray content:
yellow box 1 item 1 item 2 item 3 add new item (button)
when click on "add new item" button, "item 4" text added under item 3 text. when click on "add new item" button again, "item 5" text added under item 4 text , on...
it work expected. however, problem arises when dragging of yellow button @ top , drop in gray area, have this:
yellow box 1 item 1 item 2 item 3 item 4 item 5 add new item
yellow box 2 item 1 item 2 item 3 add new item
so when go , every time click on add new item button under yellow box 1, adds 2 new items every click instead of 1 (it add item 6 , item 7 under item 5) not wanted.
i tried cancel event bubbling , other things somehow didn't work. when isolated same scenario without using jquery ui draggable function, behaves expect. guess bug related how implemented draggable function. thank help.
here code:
$(function() { $('#content').sortable({ placeholder: 'ui-state-highlight' }); $(".top-icon").draggable({ connecttosortable: '#content', helper: myhelper, stop: handledragstop }); function myhelper(event) { return $(this).clone(); } var = 1; function handledragstop(event, ui) { var current_text = '<div class="color-box"><b>yellow box ' + + '</b>' + '<div class="yellow-content">' + '<div class="item">item 1</div>' + '<div class="item">item 2</div>' + '<div class="item">item 3</div>' + '<div class="add-item">add new item</div>' + '</div>' + '</div>'; $('#content .top-icon').after(current_text); i++; var $new_insert_item = $('#content .top-icon').next(); $('#content .top-icon').remove(); // remove clone .top-icon inside #content console.log('hi'); // when click on add new item button $('.color-box').on('click', '.add-item', function() { var $this = $(this); var item_count = $this.siblings('.item').length + 1; console.log (item_count); var str_item = ''; str_item = '<div class="item">item ' + item_count + '</div>'; $(str_item).insertbefore($this); }); } // end of handledragstop });
issue that, binding click event inside handledragstop
binds events existing dragged item existing dragged items gets click event added 1 during each drag. instead bind event outside , have event bound #content
(if container exist in dom before first drag) delegated.
$('#content').on('click', '.add-item', function () { var $this = $(this); var item_count = $this.siblings('.item').length + 1; console.log(item_count); var str_item = ''; str_item = '<div class="item">item ' + item_count + '</div>'; $(str_item).insertbefore($this); });
Comments
Post a Comment