Question

I'm using jQuery UI Draggable and I've got various points which the user can drag about, with the top/left position of every point showed in the respective results divs beneath (this will show either the original starting position of each point if its never moved, or the final position of each point if it is moved). HTML as below

<div id="container">
<div id="point1"></div>
<div id="point2"></div>
<div id="point3"></div> etc
</div>

<div id="result1"></div>
<div id="result2"></div>
<div id="result3"></div> etc

I've got the following code but for efficiency I need to use the same function below to display the results for each point. It currently works fine for showing the position of point1/result1, but I've had a brain freeze as to how to adapt it to show result2, result3 etc without simply copy/pasting the function each time!

$(document).ready(function() {

var coord = function(element) {
element = $(element);
var top = element.position().top;
var left = element.position().left;
$('#result1').text('White box: Left: ' + left + 'px ' + 'Top: ' + top + 'px');
}


$('#point1').draggable({cursor: "move", cursorAt: { top: 5, left: 5 }, containment: "#container", scroll: false,
create: function() {
    coord('#point1');
},
start: function() {
    coord('#point1');
},
stop: function() {
    coord('#point1');
}
});

I know I could probably use the child selector for all points within container instead of #point1 div, but its the function above it that I'd like to reuse each time (and then be able to take each of those values and do things with them afterwards).

Was it helpful?

Solution

I'm brand new to jQuery but I have been playing with exactly what you are doing just recently. I got around the issue by assigning a class to the DIV's. One for the draggable element and one for the dropable element. Then you can simply declare the events for the classes.

Assuming you have the following...

<div id="point1" class="point"></div>
...
<div id="result1" class="result"></div>


$( ".point" ).draggable();
$( ".result" ).droppable();

You can then assign the generic functions accordingly for each behaviour.

Hope this assists.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top