gridster.js

repository·master·Indexed 21 days ago

https://github.com/dsmorse/gridster.js

A jQuery plugin for creating draggable, multi-column grid layouts. This maintained fork of the original Ducksboard project (version 0.8.0) allows elements to span multiple columns and supports dynamically adding, removing, and resizing widgets. It includes features for serializing widget positions, programmatic movement, and a Ruby on Rails gem for integration.

Tokens
5.8K
Snippets
29
Records
35
Agent score
74%

What's inside gridster.js

  1. Integrate Gridster.js with Ruby on Rails

    master

    Gridster.js provides a gem for Ruby on Rails applications.

    1. Add the gem to your Gemfile:
    gem 'gridster.js-rails'
    1. Run bundle install.

    2. Configure your assets:

    To include the minified version in your stylesheets, add this to app/assets/stylesheets/application.css:

    *= require jquery.dsmorse-gridster.min

    To include the minified version in your JavaScript, add this to app/assets/javascripts/application.js:

    //= require jquery.dsmorse-gridster.min

    Available Asset Variants:

    • jquery.dsmorse-gridster.min (Minified)
    • jquery.gridster (Non-minified)
    • jquery.dsmorse-gridster (Non-minified)
    • jquery.dsmorse-gridster.with-extras (With extras, non-minified)
    • jquery.dsmorse-gridster.with-extras.min (With extras, minified)
  2. Manage responsive grid layouts

    master

    Gridster.js supports responsive layouts when autogenerate_stylesheet is set to true, widget_base_dimensions[0] is set to 'auto', and max_cols is not Infinity.

    When a responsive breakpoint is triggered (based on the responsive_breakpoint option), the grid can switch to a 'collapsed' mode where widgets span the full width of the container. You can manually control this behavior using toggle_collapsed_grid.

    To ensure the layout stays correct during window resizing, you should call recalculate_faux_grid to update the internal grid offsets and responsive dimensions.

    // Example of triggering a collapsed state manually
    // collapse: true to collapse, false to expand
    // opts: must include widget_margins
    gridsterInstance.toggle_collapsed_grid(true, { widget_margins: [10, 10] });
  3. Initialize Gridster

    master

    To create a draggable grid layout, instantiate the Gridster class by passing the container element and an optional configuration object. If auto_init is set to true (the default), the plugin will automatically initialize the grid. The container element should be the parent of the widgets you want to include in the grid.

    // Assuming $container is the element containing your widgets
    var gridster = new Gridster($container, {
      widget_selector: '.my-widget',
      widget_margins: [10, 10],
      // other options
    });
  4. Configure Gridster options

    master

    The Gridster constructor accepts an options object to customize the grid behavior. Key configuration categories include:

    • Widget Selection: widget_selector defines which elements are treated as widgets (default: 'li').
    • Dimensions & Spacing: widget_margins (horizontal, vertical), widget_base_dimensions (width, height), min_cols, max_cols, min_rows, and max_rows.
    • Layout Behavior: avoid_overlapped_widgets prevents overlapping during load; shift_larger_widgets_down and shift_widgets_up control how widgets move to accommodate others.
    • Styling: autogenerate_stylesheet (boolean) automatically injects CSS for positioning. If false, you must provide your own CSS using data attributes like [data-col="1"].
    • Resizing: Controlled via the resize object (e.g., resize.enabled, resize.axes, resize.min_size, resize.max_size).
    • Draggable: Controlled via the draggable object (e.g., draggable.items, draggable.distance).
  5. Iterate over grid cells with `for_each_cell`

    master

    The for_each_cell(callback, gridmap) method allows you to traverse the grid. It iterates through cells in reverse order (from the bottom-right towards the top-left).

    • callback: A function called for each cell. The signature is callback($el, c, r), where $el is the element at that cell (or null/undefined if empty), c is the column, and r is the row.
    • Breaking the loop: If the callback returns false, the iteration stops immediately.
    • gridmap (optional): The grid map to iterate over. If not provided, it defaults to the instance's this.gridmap.
    // Example: Iterate through all cells and log occupied ones
    gridsterInstance.for_each_cell(function($el, c, r) {
        if ($el) {
            console.log(`Widget found at Col: ${c}, Row: ${r}`);
        }
    });
  6. Enable or disable dragging and resizing

    master

    You can programmatically control user interaction with the grid using the following methods:

    • enable() / disable(): Toggles the ability to drag widgets.
    • enable_resize() / disable_resize(): Toggles the ability to resize widgets.
    gridster.disable(); // Stop dragging
    gridster.disable_resize(); // Stop resizing
  7. Toggle collapsed grid state

    master

    The toggle_collapsed_grid(collapse, opts) method switches the grid between its standard layout and a collapsed layout (where widgets span the full width). This is typically used when the viewport width falls below the responsive_breakpoint.

    • collapse (Boolean): If true, widgets are set to a minimum height and margins are applied to make them span the width. If false, they return to standard grid positioning.
    • opts (Object): Configuration object that must include widget_margins (an array like [horizontal, vertical]).

    When collapsing, the method automatically disables resizing and dragging if those APIs are active.

    // Collapse the grid
    gridsterInstance.toggle_collapsed_grid(true, { widget_margins: [10, 10] });
    
    // Expand the grid
    gridsterInstance.toggle_collapsed_grid(false, { widget_margins: [10, 10] });
  8. Resize widget dimensions dynamically

    master

    The resize_widget_dimensions(options) method allows you to update the grid's sizing configuration and force a recalculation of all widget dimensions.

    • options (Object): An object containing updated configuration keys:
      • widget_margins: New margin values (e.g., [10, 10]).
      • widget_base_dimensions: New base dimensions for widgets (e.g., [100, 100]).

    Calling this method triggers a full refresh: it regenerates the stylesheet, re-scans the DOM for widgets, and updates the grid height/width.

    gridsterInstance.resize_widget_dimensions({
      widget_margins: [15, 15],
      widget_base_dimensions: [120, 120]
    });
  9. Add a new widget to the grid

    master

    Use the add_widget method to dynamically insert a new widget into the grid. You can provide HTML as a string or a jQuery/HTMLElement object. If you don't specify a column or row, Gridster will find the next available position.

    // Add a widget at a specific position
    gridster.add_widget('<div class="widget">New Widget</div>', 2, 2, 1, 1);
    
    // Add a widget with size limits and a callback
    gridster.add_widget(newElement, 2, 2, 1, 1, [4, 4], [1, 1], function() {
      console.log('Widget is now visible');
    });
  10. Check if a cell is occupied

    master

    Use is_occupied(col, row) to determine if a specific grid cell is currently taken by a widget.

    Note: If the ignore_self_occupied option is enabled, the method will return false if the cell is occupied by the 'player' (the element currently being moved/interacted with), allowing for seamless swapping or movement.

    gridster.is_occupied(col, row);