How to use the grid system with drag and drop

I want to make it stay in the grid where I left it when I stop holding the mouse button here is the code

var dragging = false;
onEvent('mousereleased', function () {
    
    onEvent('update', function () {
    this.x = gridLengh * (Math.floor(mouseX/gridLengh))+gridLengh/2;
    this.y = gridLengh * (Math.floor(mouseY/gridLengh))+gridLengh/2;
});
    
    dragging = false;
});

onEvent('mousepressed', function () {
    dragging = true;
});

onEvent('update', function () {
    if(dragging) {
        
    window.gridLengh = 40;    
        
    onEvent('update', function () {
    this.x = gridLengh * (Math.floor(mouseX/gridLengh))+gridLengh/2;
    this.y = gridLengh * (Math.floor(mouseY/gridLengh))+gridLengh/2;
});

    }
});