Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Drag and drop using Javascript

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 98
    Comment on it

    If you want to drag your element from one point to another, here is the code below using Javascript:

    HTML:

    <div id="dragElement">Drag me!</div>
    

    CSS:

    #dragElement {
      width:100px;
      height:100px;
      background-color:#666;
      color:white;
      padding:10px 12px;
      cursor:move;
      top:0;
      left:0;
      position:absolute; /* we can make it relative, fixed also but not static. */
    }
    

    JS:

    var selected = null, // Moving element
        x_pos = 0, y_pos = 0, //saving the x-axis and y-axis coordinates of the mouse pointer
        x_elem = 0, y_elem = 0; // saving top, left values of the element
    
    
    function _drag_init(elem) {   // when user start dragging, this function is called
        selected = elem;
        x_elem = x_pos - selected.offsetLeft;
        y_elem = y_pos - selected.offsetTop;
    }
    
    
    function _move_elem(e) {     // when the user is dragging, this function is called
        x_pos = document.all ? window.event.clientX : e.pageX;
        y_pos = document.all ? window.event.clientY : e.pageY;
        if (selected !== null) {
            selected.style.left = (x_pos - x_elem) + 'px';
            selected.style.top = (y_pos - y_elem) + 'px';
        }
    }
    
    
    function _destroy() {   // when the user is done with dragging, this function is called
        selected = null;
    }
    
    // Bind the functions...
    document.getElementById('"dragElement').onmousedown = function () {
        _drag_init(this);
        return false;
    };
    
    document.onmousemove = _move_elem;
    document.onmouseup = _destroy;
    

    Hope this will help you with dragging.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: