Search code examples
javascriptjquerydraggable

Change the cursor to a crosshair when a button is dragged


Hello I need to turn the cursor into a crosshair while the user drags a button. The code below is not working:

$("button").draggable('cursor','crosshair');

Solution

  • To achieve this you can use cursor property of the draggable library, like this:

    $("#draggable").draggable({
        cursor: 'crosshair'
    });
    

    Alternatively, if you want to set a custom cursor through CSS you would need to use the start and end events of the jQuery draggable library to change the CSS cursor property of the ui.helper. Try this:

    $("#draggable").draggable({
      start: function(e, ui) {
        ui.helper.addClass('dragging');
      },
      stop: function(e, ui) {
        ui.helper.removeClass('dragging');
      }
    });
    .dragging { cursor: url('http://i.imgur.com/6r4pI7U.png'), crosshair; }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
    <div id="draggable">
      <p>Drag me</p>
    </div>