Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

move div with the mouse in js

// <body>

//     <div id="item"></div>
//     <div id="item1"></div>

// </body>

{
    /* <style>

    #item,#item1 {
        height: 50px;
        width: 50px;
        position: absolute;
        background: rgba(255, 166, 0, 0.562);
    } 

    </style> */
}

function moveElementDoc(id) { // id is parameter


    const element = document.getElementById(id); // we will call our id from html with this parameter

    let heightEl = element.clientHeight / 2; // half height (clientHeight = height of div)
    let widthEl = element.clientWidth / 2; //half width
    //we need it, to center our mouse in our div

    element.addEventListener("mousedown", function() {
        document.addEventListener("mousemove", movingmouse);

        function movingmouse(e) {
            element.style.position = "absolute";
            element.style.left = e.clientX - heightEl + 'px'; // position-div-"id" = positionMoveMouse"x" and "y" like bottom - height"let heightEl"
            element.style.top = e.clientY - widthEl + 'px';
            
        }

        document.addEventListener("mouseup", function() {
            document.removeEventListener("mousemove", movingmouse)
        })
    })
}


moveElementDoc("item"); //Call id in your html and place id in your getelementbyid from the parameter of function
moveElementDoc("item1");
 
PREVIOUS NEXT
Tagged: #move #div #mouse #js
ADD COMMENT
Topic
Name
2+2 =