Convert Figma logo to code with AI

daybrush logoselecto

Selecto.js is a component that allows you to select elements in the drag area using the mouse or touch.

2,039
82
2,039
88

Top Related Projects

29,388

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

21,948

:ok_hand: Drag and drop so simple it hurts

Beautiful and accessible drag and drop for lists with React

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

10,773

Infinite responsive, sortable, filterable and draggable layouts

Quick Overview

Selecto is a JavaScript library that enables drag-select functionality in web applications. It allows users to select multiple elements by dragging a selection box, similar to how you might select multiple files on a desktop. Selecto is highly customizable and can be integrated with various frameworks and libraries.

Pros

  • Easy to implement and customize
  • Supports touch devices and multiple selection methods
  • Integrates well with other libraries like Moveable and Sortable
  • Lightweight and performant

Cons

  • Limited documentation for advanced use cases
  • May require additional styling for optimal visual integration
  • Learning curve for complex scenarios
  • Potential conflicts with existing drag-and-drop implementations

Code Examples

  1. Basic usage:
import Selecto from "selecto";

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".selecto-area .cube"],
  selectByClick: true,
});

selecto.on("select", (e) => {
  e.added.forEach((el) => {
    el.classList.add("selected");
  });
  e.removed.forEach((el) => {
    el.classList.remove("selected");
  });
});
  1. Integration with Moveable:
import Selecto from "selecto";
import Moveable from "moveable";

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".target"],
});

const moveable = new Moveable(document.body, {
  target: ".target",
  draggable: true,
});

selecto.on("selectEnd", ({ isDragStart, added, removed }) => {
  if (isDragStart) {
    added.forEach((el) => {
      el.classList.add("selected");
      moveable.target = [...moveable.target, el];
    });
    removed.forEach((el) => {
      el.classList.remove("selected");
      moveable.target = moveable.target.filter((t) => t !== el);
    });
  }
});
  1. Custom key combinations:
import Selecto from "selecto";

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".item"],
  selectByClick: true,
  selectFromInside: false,
  toggleContinueSelect: ["shift"],
  keyContainer: window,
});

selecto.on("select", (e) => {
  if (e.inputEvent.shiftKey) {
    e.added.forEach((el) => {
      el.classList.add("selected");
    });
  } else {
    e.added.forEach((el) => {
      el.classList.add("selected");
    });
    e.removed.forEach((el) => {
      el.classList.remove("selected");
    });
  }
});

Getting Started

  1. Install Selecto:

    npm install selecto
    
  2. Import and initialize Selecto in your project:

    import Selecto from "selecto";
    
    const selecto = new Selecto({
      container: document.body,
      selectableTargets: [".selectable-item"],
    });
    
    selecto.on("select", (e) => {
      e.added.forEach((el) => el.classList.add("selected"));
      e.removed.forEach((el) => el.classList.remove("selected"));
    });
    
  3. Add the necessary CSS to your project:

    .selecto-selection {
      background: rgba(0, 123, 255, 0.3);
      border: 1px solid rgba(0, 123, 255, 0.5);
    }
    

Competitor Comparisons

29,388

Reorderable drag-and-drop lists for modern browsers and touch devices. No jQuery or framework required.

Pros of Sortable

  • More mature and widely adopted project with a larger community
  • Supports nested sortable lists and multi-list sorting
  • Offers additional features like auto-scrolling and touch device support

Cons of Sortable

  • Limited to drag-and-drop sorting functionality
  • May have a steeper learning curve for complex implementations
  • Larger file size compared to Selecto

Code Comparison

Selecto:

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".target"],
  selectByClick: true,
});

selecto.on("select", (e) => {
  e.added.forEach((el) => el.classList.add("selected"));
  e.removed.forEach((el) => el.classList.remove("selected"));
});

Sortable:

const sortable = new Sortable(document.getElementById('list'), {
  animation: 150,
  ghostClass: 'blue-background-class'
});

sortable.on('sort', (evt) => {
  console.log(evt.oldIndex, evt.newIndex);
});

Selecto focuses on element selection, while Sortable specializes in drag-and-drop sorting. Selecto's API is centered around selecting elements, whereas Sortable's API revolves around managing sortable lists. The code examples demonstrate their primary use cases: Selecto for selecting elements and Sortable for reordering list items.

21,948

:ok_hand: Drag and drop so simple it hurts

Pros of Dragula

  • Lightweight and simple to use, with minimal setup required
  • Supports touch events for mobile devices out of the box
  • Provides a flexible API for customizing drag and drop behavior

Cons of Dragula

  • Limited to drag and drop functionality, lacking advanced selection features
  • May require additional plugins or custom code for more complex use cases
  • Less actively maintained, with fewer recent updates compared to Selecto

Code Comparison

Selecto:

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".target"],
  selectByClick: true,
  selectFromInside: false,
});

Dragula:

const drake = dragula([
  document.getElementById('left-container'),
  document.getElementById('right-container')
]);

Key Differences

  • Selecto focuses on element selection, while Dragula specializes in drag and drop
  • Selecto offers more advanced selection features, such as lasso selection and keyboard shortcuts
  • Dragula provides a simpler API for basic drag and drop functionality
  • Selecto has more frequent updates and active development
  • Dragula has been around longer and has a larger user base

Both libraries serve different purposes and can be used together in projects requiring both selection and drag-and-drop capabilities.

Beautiful and accessible drag and drop for lists with React

Pros of react-beautiful-dnd

  • Specifically designed for React applications, offering seamless integration
  • Provides a smooth, natural dragging experience with animations
  • Extensive documentation and examples for various use cases

Cons of react-beautiful-dnd

  • Limited to list and grid layouts, less flexible for complex selections
  • Focused solely on drag-and-drop functionality, not multi-select

Code Comparison

react-beautiful-dnd:

import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';

<DragDropContext onDragEnd={onDragEnd}>
  <Droppable droppableId="list">
    {(provided) => (
      <ul {...provided.droppableProps} ref={provided.innerRef}>
        {items.map((item, index) => (
          <Draggable key={item.id} draggableId={item.id} index={index}>
            {(provided) => (
              <li ref={provided.innerRef} {...provided.draggableProps} {...provided.dragHandleProps}>
                {item.content}
              </li>
            )}
          </Draggable>
        ))}
        {provided.placeholder}
      </ul>
    )}
  </Droppable>
</DragDropContext>

Selecto:

import Selecto from "react-selecto";

<Selecto
  container={".container"}
  selectableTargets={[".selecto-area .cube"]}
  selectByClick={true}
  selectFromInside={false}
  toggleContinueSelect={["shift"]}
  hitRate={100}
  onSelect={e => {
    e.added.forEach(el => {
      el.classList.add("selected");
    });
    e.removed.forEach(el => {
      el.classList.remove("selected");
    });
  }}
/>

A set of higher-order components to turn any list into an animated, accessible and touch-friendly sortable list✌️

Pros of react-sortable-hoc

  • Specifically designed for React applications, providing seamless integration
  • Offers a higher-level abstraction for sorting and reordering elements
  • Supports both vertical and horizontal sorting out of the box

Cons of react-sortable-hoc

  • Limited to sorting and reordering functionality, less versatile for other selection tasks
  • May have a steeper learning curve for developers new to higher-order components

Code Comparison

react-sortable-hoc:

import { SortableContainer, SortableElement } from 'react-sortable-hoc';

const SortableItem = SortableElement(({value}) => <li>{value}</li>);

const SortableList = SortableContainer(({items}) => {
  return (
    <ul>
      {items.map((value, index) => (
        <SortableItem key={`item-${index}`} index={index} value={value} />
      ))}
    </ul>
  );
});

Selecto:

import Selecto from "selecto";

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".selecto-area .cube"],
  selectByClick: true,
  selectFromInside: false,
  continueSelect: false,
});

Summary

  • react-sortable-hoc is more specialized for React-based sorting tasks
  • Selecto offers broader selection capabilities beyond just sorting
  • react-sortable-hoc has a more React-centric API
  • Selecto provides a more flexible, vanilla JavaScript approach
10,773

Infinite responsive, sortable, filterable and draggable layouts

Pros of Muuri

  • More comprehensive grid layout and sorting functionality
  • Better support for responsive layouts and grid item resizing
  • Extensive animation options for item transitions

Cons of Muuri

  • Steeper learning curve due to more complex API
  • Larger file size and potentially higher performance overhead
  • Less focus on selection functionality compared to Selecto

Code Comparison

Selecto (basic selection):

const selecto = new Selecto({
  container: document.body,
  selectableTargets: [".target"],
});
selecto.on("select", e => {
  e.selected.forEach(el => el.classList.add("selected"));
});

Muuri (basic grid setup):

const grid = new Muuri('.grid', {
  items: '.item',
  dragEnabled: true,
  layout: {
    fillGaps: true
  }
});

While both libraries offer drag-and-drop functionality, Selecto focuses more on element selection, whereas Muuri provides comprehensive grid management features. Selecto's API is simpler and more straightforward for basic selection tasks, while Muuri offers more advanced grid layout and sorting capabilities at the cost of increased complexity.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Selecto.js

npm version React Preact Angular Vue Vue Svelte Lit

Selecto.js is a component that allows you to select elements in the drag area using the mouse or touch.

Demo / API / Main Project

⚙️ Installation

npm

$ npm install selecto

scripts

<script src="//daybrush.com/selecto/release/latest/dist/selecto.min.js"></script>

🚀 How to use

Option Behaviors

  • If you want to prevent select from inside and no click
    • selectFromInside: false
    • selectByClick: false (default)
  • If you want to include it regardless of hitTest when selecting from the inside
    • selectFromInside: true (default)
    • selectByClick: true
  • If you want to finish right away (selectStart and selectEnd occur at the same time) without dragging when selecting from inside
    • selectFromInside: false
    • selectByClick: true
    • preventDragFromInside: true (default)
    • clickBySelectEnd: false (default)
  • If you want to selectEnd(click) after stopping drag and mouse(touch)
    • selectFromInside: false
    • selectByClick: true
    • clickBySelectEnd: true
import Selecto from "selecto";

const selecto = new Selecto({
    // The container to add a selection element
    container: document.body,
    // Selecto's root container (No transformed container. (default: null)
    rootContainer: null,
    // The area to drag selection element (default: container)
    dragContainer: Element,
    // Targets to select. You can register a queryselector or an Element.
    selectableTargets: [".target", document.querySelector(".target2")],
    // Whether to select by click (default: true)
    selectByClick: true,
    // Whether to select from the target inside (default: true)
    selectFromInside: true,
    // After the select, whether to select the next target with the selected target (deselected if the target is selected again).
    continueSelect: false,
    // Determines which key to continue selecting the next target via keydown and keyup.
    toggleContinueSelect: "shift",
    // The container for keydown and keyup events
    keyContainer: window,
    // The rate at which the target overlaps the drag area to be selected. (default: 100)
    hitRate: 100,
});

selecto.on("select", e => {
    e.added.forEach(el => {
        el.classList.add("selected");
    });
    e.removed.forEach(el => {
        el.classList.remove("selected");
    });
});

Do you want to select accurately?

Since selecto basically checks using getBoundingClientRect, it is not accurate if the object is rotated or distorted.

If you want to check accurately, use getElementRect option with the following code

import Selecto from "selecto";
import { getElementInfo } from "moveable"; // (13kb function) if you use react, use react-moveable

const selecto = new Selecto({
    ...,
    // (target: HTMLElement | SVGElement ) => { pos1: number[], pos2: number[], pos3: number[], pos4: number[] }
    // pos1: left top
    // pos2: right top
    // pos3: left bottom
    // pos4: right bottom
    getElementRect: getElementInfo,
});

📦 Packages

Package Name Version Description
react-selectoA React Selecto Component that allows you to select elements in the drag area using the mouse or touch.
ngx-selectoAn Angular Selecto Component that allows you to select elements in the drag area using the mouse or touch.
vue-selectoA Vue 2 Selecto Component that allows you to select elements in the drag area using the mouse or touch.
vue3-selectoA Vue 3 Selecto Component that allows you to select elements in the drag area using the mouse or touch.
preact-selectoA Preact Selecto Component that allows you to select elements in the drag area using the mouse or touch.
svelte-selectoA Svelte Selecto Component that allows you to select elements in the drag area using the mouse or touch.
lit-selectoA Lit Selecto Component that allows you to select elements in the drag area using the mouse or touch.

⭐️ Show Your Support

Please give a ⭐️ if this project helped you!

👏 Contributing

If you have any questions or requests or want to contribute to selecto or other packages, please write the issue or give me a Pull Request freely.

🐞 Bug Report

If you find a bug, please report to us opening a new Issue on GitHub.

📝 License

This project is MIT licensed.

MIT License

Copyright (c) 2020 Daybrush

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

NPM DownloadsLast 30 Days