javascripthaskell-snap-frameworkinteract.js

Dynamic modification of snapping values


I start with interract.js and try to figure out how to snap my elements to defined sizes in the index targets. It works well when I set the values statically but actually I would like to dynamize the values so that each element can snap to each other. I didn't find how to do this in the doc, would you have a research track allowing me to make the values evolve according to the displacement of the blocks, so that they become "snappable" ?

ideally I think these values should be able to change dynamically each time you move an element, so using dragend event, but how do you make the change in values take effect... thank you for your feedback.

// here I define my static values for the snap
var dynamicRestrictions = [
        {x: 200, range: 20},
        {x: 400, range: 20},
        {y: 300, range: 20}
    ];

interact('.resize-drag')
    .draggable({
        inertia: true,
        modifiers: [
            interact.modifiers.snap({
                targets: dynamicRestrictions, // <= how to dynamic edit them ?
                relativePoints: [
                    {x: 0, y: 0},
                    {x: 1, y: 1},
                    {x: 0, y: 1},
                    {x: 1, y: 0},
                ],
                offset: 'parent'
            }),
            ],
            autoScroll: true,
            listeners: {              
                move: dragMoveListener,
            }
        })

Solution

  • you can use a function on the onstart event.

    .draggable({
        //...
        onstart: dragMoveStartListener,
        //...
    })
    

    which will allow you to set your hang values.

    function dragMoveStartListener(event) {
        var element = $(event.target);
        dynamicRestrictions.length = 0;
        $('.resize-drag').each(function () {
            if (!$(this).is(element)) {
                var thisPosition = $(this).position(),
                    snapX = thisPosition.left,
                    snapY = thisPosition.top,
                    snapWidth = $(this).width(),
                    snapHeight = $(this).height(),
                    range = 20;
                var sumWidth = parseInt(snapX + snapWidth),
                    sumHeight = parseInt(snapY + snapHeight);
                dynamicRestrictions.push({x: snapX, y: snapY, range: 10});
                dynamicRestrictions.push({x: snapX, range: range});
                dynamicRestrictions.push({x: sumWidth, range: range});
                dynamicRestrictions.push({y: snapY, range: range});
                dynamicRestrictions.push({y: sumHeight, range: range});                      
            }
        });
    }
    

    I tested it and it works pretty well, except that I don't know how to snap both vertically and horizontally, each time it's one or the other... looking for a little bit more, should do the job