YUI3 - Update CSS class based on XY position

118 views Asked by At

I am using the drag and drop to be able to move one of my nodes within a page. What I want to be able to do is once the drag and drop is completed, get the XY position and if it is outside a certain position (XY), then the class applied to the node should be updated.

http://jsfiddle.net/gabrielesandoval/ab1cjrcj/

CSS:

.dd-demo-inside {
background-color: #8DD5E7;
color: #000;
}
.dd-demo-outside {
background-color: #004C6D;
}    

JS:

YUI().use('dd-constrain', function(Y) {
   var dd1 = new Y.DD.Drag({
    node: '#dd-demo-1'
}).plug(Y.Plugin.DDConstrained, {
    constrain2node: '#dd-demo-canvas1'
});
});

So in the JS fiddle example above, if the box moves to the outer color, then the CSS applied to "dd-demo-1" should change from .dd-demo-inside to .dd-demo-outside.

I know YUI has a getXY() function but I wasnt sure how the best way to use it or what event it can be used on to make sure it is called once the dragging of the node is completed.

Any help you can provide would be much appreciated.

3

There are 3 answers

0
Link On

Once you release you can call a function that uses javascript to retrieve the X and Y offset and update the class accordingly. Assuming you're using jQuery it could look something like this.

var offset = $(element).offset();
if(offset.left > x && offset.top > y) {
  element.addClass(newClass);
 }

I built onto your JSFiddle to show how it would work http://jsfiddle.net/ab1cjrcj/12/

0
Gabriel On

So i updated my own code. I subscirbed to the drag:end event--

dd1.on('drag:end', getOffsetTop);

Then I make a pure JS function that just checks for the offsetTop and offsetLeft. I think I should be able to create my own condition based on these values to change the class names.

1
PottyBert On

You can use the Node.inRegion method to test if the node is inside another node, passing true as the second parameter will ensure that it is fully inside the target region.

http://jsfiddle.net/ab1cjrcj/16/

YUI().use('dd-constrain', function(Y) {
    var dragNode = Y.one('#dd-demo-1'), 
        innerCanvasNode = Y.one('#dd-demo-canvas3'),
        dd1;

    dd1 = new Y.DD.Drag({
        node: dragNode
    }).plug(Y.Plugin.DDConstrained, {
        constrain2node: '#dd-demo-canvas1'
    });

    dd1.on('drag:end', function(e){
        if (dragNode.inRegion(innerCanvasNode, true)){
            dragNode.replaceClass('dd-demo-outside', 'dd-demo-inside');
        } else {
            dragNode.replaceClass('dd-demo-inside', 'dd-demo-outside');
        }
        //console.log(dragNode.inRegion(innerCanvasNode, true));
    });

});