I'm doing a dashboard using Gridster. I have next code html:
<div class="gridster">
<ul id="widget_list">
<li id="widg-1" data-row="1" data-col="1" data-sizex="2" data-sizey="2">1
<a class='remove' href='#'>×</a>
</li>
<li id="widg-2" data-row="1" data-col="1" data-sizex="2" data-sizey="2">2
<a class='remove' href='#'>×</a>
</li>
<li id="widg-3" data-row="1" data-col="1" data-sizex="2" data-sizey="2">3
<a class='remove' href='#'>×</a>
</li>
<li id="widg-4" data-row="1" data-col="1" data-sizex="2" data-sizey="2">4
<a class='remove' href='#'>×</a>
</li>
</ul>
</div>
<button id="addWidget" data-role="button">Add widget</button>
And here, my code Javascript:
var gridster;
$(function(){
var log = document.getElementById('log');
gridster = $(".gridster ul").gridster({
widget_base_dimensions: [100, 55],
widget_margins: [5, 5],
autogrow_cols: true,
resize: {
enabled: true
}
}).data('gridster');
$(document).on( "click", "#addWidget", function(e) {
e.preventDefault();
var li = $('#widget_list li').last();
var data = li.attr("id");
var array = data.split('-');
var id = array[1];
id++;
gridster.add_widget.apply(gridster, ['<li id="widg-' + id + '">' + id + '<a class="remove" href="#">×</a></li>', 2, 2]);
});
$(".remove").click(function(){
var id=$(this).parent().attr("id");
alert(id);
gridster.remove_widget($(".gridster ul").find("[id='" + id + "']"));
});
});
The problem is when I wanna remove a new widget which I added dynamically just before. When I wanna remove the widget which It's already added (the four ones), The function works perfectly. On the other case, it doesn`t work. The only thing strange I have seen, the program add "style="display: list-item;" as a param in the new created widget.
Anyone can help me? Thanks!
The problem you are facing is of jQuery nature. All dynamically created elements are missing the declared binding for the remove action.
You should change the event handler to this:
$(document).on('click', '.remove', function(){
var id=$(this).parent().attr("id");
alert(id);
gridster.remove_widget($(".gridster ul").find("[id='" + id + "']"));
});