Search code examples
javascripthtmlcssdraggable

Trying to add dragging boundary to an image hidden on overflow


i'm trying to add boundary to this code where i could drag the image to see what parts are hidden without dragging it too much in a way where the background is visible which means when the lower boundary of the image for example reaches the lower boundary of the container it stops moving in that direction

var offset = [0,0];
var mouse_is_down = false

function copie_click(elem, e) {
    mouse_is_down = true;
    offset = [elem.offsetLeft - e.clientX, elem.offsetTop - e.clientY];
}

function copie_unclick(elem, e) {
    mouse_is_down = false;
}

function copie_move(elem, e) {
    e.preventDefault(); // if this is removed mouse will unclick on move
    if (mouse_is_down) {
        elem.style.left = (e.clientX + offset[0]) + 'px';
        elem.style.top  = (e.clientY + offset[1]) + 'px';
    }
}
.mark_item_large {
    width: 200px;
    height: 200px;
    margin: 0 auto;
    padding: 1em;
    border-radius: 10px;
    margin-bottom: 0.5em;
    font-weight: 700;
    border: 1px solid black;
}

.mark_item_image {
    width: 100%;
    position: relative;
    height: 100%;
    overflow: hidden;
}

.mark_item_image > img {
    position: absolute;
    right: 0;
    top: 0;
    width: 200%;
}
        <div class="mark_item_large">
            <div class = "mark_item_image">
                <img src="https://static.wixstatic.com/media/f844a81ff14743ba92ef5f4f498aa2c8.jpeg/v1/fill/w_940,h_495,al_c,q_85,usm_0.66_1.00_0.01/f844a81ff14743ba92ef5f4f498aa2c8.webp" alt="copie preview" onmousedown="copie_click(this, event)" onmouseup="copie_unclick(this, event);" onmousemove="copie_move(this, event);">
            </div>
            .... other stuff here
        </div>


Solution


  • i solved it my self by doing this !

    function copie_click(elem, e) {
        mouse_is_down = true;
        offset = [elem.offsetLeft - e.clientX, elem.offsetTop - e.clientY];
    }
    
    function copie_unclick(elem, e) {
        mouse_is_down = false;
    }
    
    function copie_move(elem, e) {
        e.stopPropagation();
        e.preventDefault(); // if this is removed mouse will unclick on move
        if (mouse_is_down) {
            if ((e.movementX > 0 && e.target.offsetLeft < 0 ) || (e.movementX < 0 && -e.target.offsetLeft < (e.target.offsetWidth - e.target.parentElement.offsetWidth)))
                elem.style.left = (e.clientX + offset[0]) + 'px';
            if ((e.movementY > 0 && e.target.offsetTop < 0 )|| (e.movementY < 0 && e.target.offsetTop > -(e.target.offsetHeight - e.target.parentElement.offsetHeight) ) )
                elem.style.top  = (e.clientY + offset[1]) + 'px';
        }
        disable_click = true;
    }