Search code examples
javascriptjqueryonclickgridster

gridster add widget on button click


I'm evaluating gridster jquery plugin for customizing a dashboard and it seems perfect for my needs. But there's something i can't get working. I want to add a new widget dynamically when an 'add button' is clicked, using the add_widget function documented in the library. The result is that the widget seems to be added but then disappears and everything rolls back to the initial state.

$(function(){
    gridster = $(".gridster ul").gridster({
                widget_base_dimensions: [100, 120],
                widget_margins: [5, 5],
                draggable: {
                    handle: '.dragDiv'
                }
    }).data('gridster');   
    gridster.add_widget.apply(gridster, ['<li>new</li>', 1, 2]);

    $(document).on( "click", "#addWidgetButton", function() { 
       gridster.add_widget.apply(gridster, ['<li>new</li>', 1, 2]);
    });
});

Look at this jsfiddle.

As you can see in the example I use the same function to add a widget first in the general scope (and it works), and then in the button click event handler but it doesn't work properly.

What's wrong?


Solution

  • You should disable the default click event of the button.

    Right code:

    $(document).on( "click", "#addWidgetButton", function(e) {
         e.preventDefault(); 
         gridster.add_widget.apply(gridster, ['<li>new</li>', 1, 2]);
    });