lf2com / magnet.js

Magnet.js is a JavaScript library that groups HTML elements and makes them attractable to each other
MIT License
82 stars 15 forks source link

Prevent dragging when using Jquery UI resizable #17

Open JGInitiatives opened 4 years ago

JGInitiatives commented 4 years ago

Hi.

How can i prevent my block from moving when i resize it with jQuery UI Resizable ?

Thank you in advance.

lf2com commented 4 years ago

Hi @JGInitiatives,

What's the condition when you resizing block? If it's possible to setup a switch to turn on/off the function of resize, I would recommend you to use $block.allowDrag(false); when resizing. And set it to true when not to resize. If the block supports functions of dragged and resized at the same time, we have to handle mouse/touch event ourselves. I could provide a simple sample code if you need. The only problem is I might spend a little time for it. If it is urgent for you, you can refer to #14, which is a related issue with interactjs.

JGInitiatives commented 4 years ago

Hi,

Thank you for your reply.

When I resize a block (= mousedown on an edge of the block and move), I also drag the block at the same time.

I tried to use allowDrag(false) when resizing, but when the resizing starts, the drag event has already started, and allowDrag(false) works only after I release the click.

You would be really kind to provide me with an example code, It's not necessary urgent, don't worry !

lf2com commented 4 years ago

I wrote a sample code. The key is as follows:

const _edge = 10; // set a edge

// create a magnet group
const $magnet = $.magnet({
    distance: 15,
    attractable: true,
    allowCtrlKey: true,
    allowDrag: false, // set false here because we will handle the drag event ourselves
});

// handle mouse down event
$YOUR_BLOCK.on('mousedown', function(e) {
    const self = this;
    const dx = e.offsetX;
    const dy = e.offsetY;
    const rect = self.getBoundingClientRect();
    self.style.zIndex = 10;
    if ((rect.width - dx) < _edge && (rect.height - dy) < _edge) {
        return; // for resizing block
    }
    $(document)
        .on('mousemove.magnet', function(evt) {
            // manually call .handle() to ask $magnet to handler the rectangle
            $magnet.handle(self, {
                x: (evt.clientX - dx),
                y: (evt.clientY - dy),
                width: rect.width,
                height: rect.height,
            });
        })
        .on('mouseup.magnet', function() {
            $(this).off('mousemove.magnet mouseup.magnet');
        });
});

$magnet.add($YOUR_BLOCK); // remember to add your block into magnet group
JGInitiatives commented 4 years ago

Hi !

It sounds perfect ! I'm going to try.

Thank you !