cssdrag-and-dropangular-material

How can I change the cursor when dragging? Material CDK Drag and Drop


Using the Drag and Drop behavior from the Material CDK library, I'm trying to change the cursor upon dragging a cdkDrag element.

For example, in this StackBlitz the cursor is grab upon hover. I'd like it to change to grabbing upon drag. An example of this is what happens when grabbing a row in Google Sheets:

enter image description here

Reading the documentation for styling a drag and drop component, it looks like adding a cursor property to this class should do the trick:

.cdk-drop-list-dragging: A class that is added to cdkDropList while the user is dragging an item.

The code looks like this:

.example-box {
  /* other CSS properties */
  cursor: grab;
}

.cdk-drop-list-dragging {
  cursor: grabbing;
}

However, as you can see in the StackBlitz, that doesn't seem to change the cursor. I'm guessing this is because this class applies to the list and not the cursor.

Another potential was the .cdk-drag-preview class:

.cdk-drag-preview: This is the element that will be rendered next to the user's cursor as they're dragging an item in a sortable list. By default the element looks exactly like the element that is being dragged.

This doesn't seem to work either. I think it's because it changes the element rendered next to the cursor and not the cursor itself.

Any ideas on how to get the cursor to change while dragging?


Solution

  • Just add cursor: grabbing to your example-box:active

    .example-box:active {
      box-shadow: 0 5px 5px -3px rgba(0, 0, 0, 0.2),
                  0 8px 10px 1px rgba(0, 0, 0, 0.14),
                  0 3px 14px 2px rgba(0, 0, 0, 0.12);
      cursor: grabbing;
    }
    

    The :active selector is used to select and style the active link.

    A link becomes active when you click on it.

    Tip: The :active selector can be used on all elements, not only links.

    Additional information here

    https://www.w3schools.com/cssref/sel_active.asp


    Stackblitz

    https://stackblitz.com/edit/angular-b8kjj3-r993mc?embed=1&file=app/cdk-drag-drop-overview-example.css