Search
 
SCRIPT & CODE EXAMPLE
 

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");
Comment

PREVIOUS NEXT
Code Example
Javascript :: json to csv nodejs 
Javascript :: Vue use props in style 
Javascript :: console table js 
Javascript :: jquery migrate 
Javascript :: how to validate a string using regular expression in javascript 
Javascript :: jquery if data attribute exists 
Javascript :: javascript negative infinity 
Javascript :: get month in two digit in javascript date 
Javascript :: compose es6 
Javascript :: svelte ondestroy 
Javascript :: react native text input right 
Javascript :: javascript push array into array 
Javascript :: react 404 page not found 
Javascript :: replace line break with html line break js 
Javascript :: how to get innerhtml value in javascript 
Javascript :: toaster cdn 
Javascript :: javascript append to array 
Javascript :: cypress custom error message 
Javascript :: how to see if the window has focus in js 
Javascript :: Nuxt: Nuxt auth not redirecting after logout 
Javascript :: add key vakue to front of object 
Javascript :: swal con input 
Javascript :: remove double slash from url javascript 
Javascript :: js first letter to uppercase 
Javascript :: fileupload progress bar in axios 
Javascript :: moment now format 
Javascript :: jquery selector this and class 
Javascript :: how to make a textarea unwritable in react native 
Javascript :: get if user signed in firebase 
Javascript :: how to specify max number of character angular mat input 
ADD CONTENT
Topic
Content
Source link
Name
5+6 =