DobotJr
DobotJr

Reputation: 4049

Get ID of element being dragged

Using the code below, how can I get the id of an element being dragged? And then, if the element ID does not equal 1 then revert element to original position?

Thanks,

<script> //DRAG AND DROP EVENTS
    $(".container").delegate(".draggable","mouseenter",function() {
        $(".draggable").draggable({      
            revert : function(event, ui) {
                $(this).data("uiDraggable").originalPosition = {
                    top  : 0,
                    left : 0
                };
                return !event;
            },
            start: function(event,ui) {  // GET ID OF ELEMENT HERE IS NOT WORKING 
              var id = ui.draggable.attr("id");
              console.log(id);
              //GETTING ERROR Uncaught TypeError: Cannot read property 'attr' of undefined
              //IF id <> 1 then revert to original position 
            }
        });

    });
    </script>

Upvotes: 1

Views: 1372

Answers (2)

hillai
hillai

Reputation: 93

Try this:

start: function(event, ui) {
   var id = event.target.id;
   console.log(id);
}

Upvotes: 1

T J
T J

Reputation: 43156

Inside the function which you pass to the revert option, this will refer to the jQuery object corresponding to the element being dragged - You can access it's id using this.attr("id").

Side notes:

  • You've initializing the draggable inside an event handler - everytime the event is triggered, draggable will be reinitialized... You might want to move the initialization out side.
  • The revert callback doesn't have the event or ui parameters, the only argument it seems to receive is a boolean
  • The ui parameter inside start callback doesn't have a draggable property
  • It's a good idea to refer the documentation instead of making assumptions

$(".draggable").draggable({
  revert: function (event, ui) {
     return (this.attr("id")==1);
  }
});
div {
    width:50px;
    height:50px;
    line-height:50px;
    margin:5px;
    text-align:center;
    background:red;
    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.1/jquery-ui.min.js"></script>
<div id="1" class="draggable">1</div>
<div id="2" class="draggable">2</div>

Upvotes: 1

Related Questions