Ravi Vasani Ravi Vasani - 5 months ago 38
CSS Question

Drag and drop events in Jquery UI

I am learning jQuery draggable and droppable UI in that i am facing problem of handling events,

here is the my code

CSS:

#draggable
{
width: 100px;
height: 100px;
background: blue;
}
#droppable
{
position: absolute;
left: 250px;
top: 0;
width: 125px;
height: 125px;
background: red;
color: #fff;
padding: 10px;

}


HTML:

<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript" src="jquery-ui.min.js"></script>

<div id="droppable">Drop here
<label id="l1"></label>
</div>
<div id="draggable"><input type="text" style="width: 90px;" id="t1"></div>


javascript:

var text;
$( "#draggable").draggable({
revert: true ,

stop: function(){
alert("over");

document.getElementById('t1').value = "";
}

});
$( "#droppable" ).droppable({
drop: function() {
alert( "dropped" );
text = document.getElementById('t1').value;
console.log(text);
document.getElementById('l1').innerHTML = text;
}
});


Here when draggable div drops, I want to set the text that is in textbox of draggable to label that is in droppable div but some how text is not set

so please help me with this, I know I have make silly mistake in this but i am able to find it.

Thank you so much for your time.

Dar Dar
Answer

I am not sure if I understood what you asked correctly but I wish this would help.

You can use jQuery throughout if you wish.

element.val(""); to set the text of an element.

text = draggableText.val(); to get the text of an element.

droppableText.text(text); to set the text of a label.

jsFiddle: https://jsfiddle.net/5mrz37wn/

CSS:

#draggable {
  width: 100px;
  height: 100px;
  background: blue;
}

#droppable {
  position: absolute;
  left: 250px;
  top: 0;
  width: 125px;
  height: 125px;
  background: red;
  color: #fff;
  padding: 10px;
}

HTML:

<div id="droppable">Drop here
  <label id="l1"></label>
</div>
<div id="draggable">
  <input id="t1" type="text" style="width: 90px;">
</div>

JavaScript:

var text;
var draggableText = $("#t1");
var droppableText = $("#l1");

$("#draggable").draggable({
  revert: true,
  stop: function() {
    alert("over");
    draggableText.val("");
  }

});
$("#droppable").droppable({
  drop: function() {
    alert("dropped");
    text = draggableText.val();
    console.log(text);
    droppableText.text(text);
  }
});

Some references for your jQuery study:

http://api.jquery.com/val/

http://api.jquery.com/text/

You can always refer to these documents to find more about the available methods.