InfoHeap
Tech
Navigation
  • Home
  • Tutorials
    • CSS tutorials & examples
    • CSS properties
    • Javascript cookbook
    • Linux/Unix Command Line
    • Mac
    • PHP
      • PHP functions online
      • PHP regex
    • WordPress
  • Online Tools
    • Text utilities
    • Online Lint Tools
search

Javascript

    Javascript strings

    • Javascript - check if string is number
    • Javascript - parseInt
    • string ends with check
    • string starts with check

    Javascript Array

    • array forEach
    • array append item
    • array remove last item
    • array prepend item
    • array remove first item
    • create array from 0 to N-1
    • convert array to json string

    Javascript control flow

    • for-in loop to iterate over keys of javascript object

    Javascript DOM

    • Javascript - DOM appendChild example
    • Javascript - get computed style of an element
    • Javascript - how to view text inside DOM element
    • Javascript - img onload examples
    • Javascript - ready vs on load event handler example
    • Javascript - use querySelector to set dom element html
    • Javascript DOMContentLoaded listener example
    • Javascript event bubble vs capture
    • Javascript how to stop event propagation
    • Javascript onscroll event handler
    • Javascript onscroll event handler with throttling
    • Make an element draggable using Vanilla Javascript
    • Multiple onload handlers using vanilla Javascipt
    • Use universal selector to get all DOM nodes in vanilla Javascript
    • document querySelector examples
    • dump all handlers on window object

    Javascript Cookbook

    • Are Javascript functions objects?
    • Declare and invoke anonymous function
    • HTML5 drag and drop
    • JSLint on command line on Ubuntu
    • Javascript - call vs apply
    • Javascript - implement class using function
    • Javascript - iterate over function arguments
    • Javascript - print all methods of an object
    • Javascript - run a function at regular interval
    • Javascript - textarea and text input select all
    • Javascript arrow function examples
    • Javascript check if variable is defined
    • Javascript local and global variables
    • Javascript parse json string
    • Javascript prototype examples
    • Javascript settimeout example
    • Javascript sleep implementation
    • Requirejs - quickstart guide for beginners
    • catch errors using window.onerror
    • print javascript object to log

    Javascript libraries

    • AngularJS
    • CasperJS
    • PhantomJS
    • React
    • jQuery

    Javascript global functions

    • Javascript - Number function
     
    • Home
    • > Tutorials
    • > Javascript

    Make an element draggable using Vanilla Javascript

    on Apr 17, 2016

    Javascript event handler mousedown and mousemove can be used to make an element draggable without using any other library. This can be made to work on mobile also using touchstart and touchmove. For the purpose of this example, we’ll only focus on desktop.

    Here is the overflow code flow:

    1. The element which we want to make draggable should be positioned element (relative, absolute or fixed).
    2. Store element page position on mousedown using element.offsetLeft and element.offsetTop
    3. Store click event’s page position on mousedown using event.pageX and event.pageY. Note that this will be slightly different from element’s position depending upon where did use click within element.
    4. Change state inDrag to true on mousedown
    5. onmousemove, change element’s position using element.style.left and element.style.top.
    6. onmouseup set state inDrag=false.
    7. Note that mousemove and mouseup are attached to document. This will handle the case of user moving mouse too fast.
    <style type="text/css">
    #drag1 {position:relative; width:100px; background-color: lightblue;}
    </style>
    <div id="drag1">Drag me</div>
    
    <script>
    (function(elementSelector) {
      var dragStartX, dragStartY; var objInitLeft, objInitTop;
      var inDrag = false;
      var dragTarget = document.querySelector(elementSelector);
      dragTarget.addEventListener("mousedown", function(e) {
        inDrag = true;
        objInitLeft = dragTarget.offsetLeft; objInitTop = dragTarget.offsetTop;
        dragStartX = e.pageX; dragStartY = e.pageY;
      });
      document.addEventListener("mousemove", function(e) {
        if (!inDrag) {return;}
        dragTarget.style.left = (objInitLeft + e.pageX-dragStartX) + "px";
        dragTarget.style.top = (objInitTop + e.pageY-dragStartY) + "px";
      });
      document.addEventListener("mouseup", function(e) {inDrag = false;});
    }("#drag1"))
    </script>
    refresh done
    try it online

    Suggested posts:

    1. Javascript parse json string
    2. Multiple onload handlers using vanilla Javascipt
    3. Python itertools imap examples
    4. CSS :nth-last-of-type
    5. CSS animation shorthand property
    6. CSS opacity – set opacity level of an element
    7. PHP – get calling file name and line number using debug_backtrace
    8. Javascript sleep implementation
    Share this article: share on facebook share on linkedin tweet this submit to reddit
    Posted in Tutorials | Tagged Javascript, Javascript DOM, Tutorials
    • Browse content
    • Article Topics
    • Article archives
    • Contact Us
    Popular Topics: Android Development | AngularJS | Apache | AWS and EC2 | Bash shell scripting | Chrome developer tools | Company results | CSS | CSS cookbook | CSS properties | CSS Pseudo Classes | CSS selectors | CSS3 | CSS3 flexbox | Devops | Git | HTML | HTML5 | Java | Javascript | Javascript cookbook | Javascript DOM | jQuery | Kubernetes | Linux | Linux/Unix Command Line | Mac | Mac Command Line | Mysql | Networking | Node.js | Online Tools | PHP | PHP cookbook | PHP Regex | Python | Python array | Python cookbook | SEO | Site Performance | SSH | Ubuntu Linux | Web Development | Webmaster | Wordpress | Wordpress customization | Wordpress How To | Wordpress Mysql Queries | InfoHeap Money

    Copyright © 2025 InfoHeap.

    Powered by WordPress