Magic Grid

repository·master·Indexed 25 days ago

https://github.com/e-oj/magic-grid

A lightweight JavaScript library for creating dynamic, masonry-style grid layouts, specifically designed for content with varying heights. Version 3.4.7 provides a configuration-based constructor to manage item positioning via CSS transforms or top/left properties, with built-in support for static and dynamic content, window resize listeners, and a ResizeObserver for container changes.

Tokens
1.9K
Snippets
8
Records
14
Agent score
35%

What's inside magic-grid

  1. Install Magic Grid

    master

    You can install Magic Grid via NPM or include it directly in your HTML using a CDN.

    npm install magic-grid
    <!-- CDN -->
    <script src="https://unpkg.com/magic-grid/dist/magic-grid.cjs.js"></script>
    
    <!-- Minified CDN -->
    <script src="https://unpkg.com/magic-grid/dist/magic-grid.min.js"></script>
  2. Initialize Magic Grid for static content

    master

    Use the static: true option if all child elements of your container are already present in the DOM and do not change dynamically.

    let magicGrid = new MagicGrid({
      container: "#container", // Required. Can be a class, id, or an HTMLElement.
      static: true, // Required for static content.
      animate: true, // Optional.
    });
    
    magicGrid.listen();
  3. Initialize Magic Grid for dynamic content

    master

    If your container loads content from an API or experiences rendering delays, you must provide the items count to let the grid know how many items to expect.

    let magicGrid = new MagicGrid({
      container: "#container", // Required. Can be a class, id, or an HTMLElement.
      items: 20, // For a grid with 20 items. Required for dynamic content.
      animate: true, // Optional.
    });
    
    magicGrid.listen();
  4. Configure MagicGrid constructor

    master

    The MagicGrid constructor initializes the grid with a configuration object.

    Note: Every item in the grid must have the same width.

    let magicGrid = new MagicGrid({
      container: "#container", // Required. Can be a class, id, or an HTMLElement
      static: false, // Required for static content. Default: false.
      items: 30, // Required for dynamic content. Initial number of items in the container.
      gutter: 30, // Optional. Space between items. Default: 25(px).
      maxColumns: 5, // Optional. Maximum number of columns. Default: Infinite.
      useMin: true, // Optional. Prioritize shorter columns when positioning items? Default: false.
      useTransform: true, // Optional. Position items using CSS transform? Default: True.
      animate: true, // Optional. Animate item positioning? Default: false.
      center: true, // Optional. Center the grid items? Default: true. 
    });
  5. Reference Magic Grid API methods

    master

    MagicGrid(config)

    Initializes the grid with a configuration object.

    .listen()

    Positions the items and listens for changes to the window size. All items are repositioned whenever the window is resized. The library also listens for changes in container size.

    .positionItems()

    Manually triggers a repositioning of items. Useful when new elements are added to the container.

    .onReady(callback)

    Adds a listener that executes a function once the grid is ready. Returns a unique ID.

    .onPositionComplete(callback)

    Adds a listener that executes a function whenever positionItems is called (including initial setup and window/container resizing). Returns a unique ID.

    .removeListener(id)

    Removes a listener by its unique ID.

  6. Listen for grid events

    master

    MagicGrid provides two primary lifecycle events that you can subscribe to using callback functions:

    • onReady(callback): Triggered when the grid determines all expected items (defined by the items config) are present in the DOM.
    • onPositionComplete(callback): Triggered after the items have been successfully positioned in the grid.

    These methods return the result of the underlying addListener call.

  7. Initialize MagicGrid with a configuration object

    master

    To use MagicGrid, instantiate the MagicGrid class with a configuration object. The grid manages the positioning of child elements within a container.

    Configuration Options:

    • container: The HTMLElement or a CSS selector string for the grid container.
    • items: The number of items expected to be in the grid (used to determine when the grid is ready).
    • gutter: The spacing (in pixels) between grid items.
    • static: Boolean. If true, the grid does not wait for items to load before initializing.
    • maxColumns: Optional number to limit the maximum number of columns.
    • useMin: Boolean. If true, items are placed in the shortest column (Masonry style). If false, items are placed sequentially.
    • useTransform: Boolean. If true, uses transform: translate() for positioning instead of top/left (better performance).
    • animate: Boolean. Enables CSS transitions for item movement.
    • center: Boolean. If true, the grid items are centered within the container when there is leftover whitespace.

    Note: The grid automatically listens for window resize events and container resizing to reposition items.

  8. Update the grid container using setContainer()

    master
    If the DOM element acting as the grid container changes, use setContainer(container) to update the instance. This method automatically updates the internal ResizeObserver to watch the new container instead of the old one.
  9. Start the MagicGrid lifecycle with listen()

    master

    Call listen() to begin the grid's operation. This method:

    1. Checks if the grid is ready() (all items loaded).
    2. If not ready, it starts a polling interval to check for items.
    3. If ready, it attaches a resize event listener to the window, initializes a ResizeObserver for the container, and performs the initial positionItems() call.
    4. Emits the READY_EVENT once initialized.
  10. Listen for grid readiness with .onReady()

    master

    Adds a listener that executes a callback function once the grid is ready. Returns a unique id that can be used to remove the listener.

    const id = magicGrid.onReady(() => {
      console.log("Grid is ready");
    });