Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 4006422
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 20, 20262026-05-20T08:30:46+00:00 2026-05-20T08:30:46+00:00

I’m trying to make a drag-and-drop engine in JavaScript. Right now, I’m adding a

  • 0

I’m trying to make a drag-and-drop engine in JavaScript. Right now, I’m adding a bounds feature which will trap the .drag object inside its parent element. However, to do this, I need to understand how positioning works in html, and I don’t. Can anyone thoroughly explain it?

Javascript Engine:

// JavaScript Document

var posX;
var posY;
var element;
var currentPos;

document.addEventListener("mousedown", drag, false);

function drag(event) {
    if(~event.target.className.search(/drag/)) {
        element = event.target;
        element.style.zIndex="100";
        currentPos = findPos(element);
        posX = event.clientX -currentPos.x;
        posY = event.clientY -currentPos.y;
            if(~event.target.className.search(/bound/))
                document.addEventListener("mousemove", boundMovement, false);
            else
                document.addEventListener("mousemove", freeMovement, false);
    }
}

function freeMovement(event) { // This functions works

    if (typeof(element.mouseup) == "undefined")
        document.addEventListener("mouseup", drop, false);
    //Prevents redundantly adding the same event handler repeatedly

    element.style.left = event.clientX - posX + "px";
    element.style.top = event.clientY - posY + "px";
}

function boundMovement(event) { // This function doesn't work

    if (typeof(element.mouseup) == "undefined")
        document.addEventListener("mouseup", drop, false);
    //Prevents redundantly adding the same event handler repeatedly

    // Below logic is false- I wish to understand why =]
    currentPos = findPos(element.offsetParent);
    if((event.clientX - posX) <= currentPos.x)
        element.style.left = event.clientX - posX + "px";
    if((event.clientY - posY) <= currentPos.y)
        element.style.top = event.clientY - posY + "px";
}

function drop() {
    element.style.zIndex="1";
    document.removeEventListener("mousemove", boundMovement, false);
    document.removeEventListener("mousemove", freeMovement, false);
    document.removeEventListener("mouseup", drop, false);
    //alert("DEBUG_DROP");
}

function findPos(obj) { // Donated by `lwburk` on StackOverflow
    var curleft = curtop = 0;
    if (obj.offsetParent) {
        do {
            curleft += obj.offsetLeft;
            curtop += obj.offsetTop;
        } while (obj = obj.offsetParent);
        return { x: curleft, y: curtop };
    }
}

Here is the CSS I am using:

@charset "utf-8";
/* CSS Document */

.drag {
    position: absolute;
    -webkit-user-select: none;
    -moz-user-select: none;
    user-select: none;
}

.bound {
    /* Class to signify that the drag_object can not leave the parent element */
    ;
}

.square {
    width: 100px;
    height: 100px;
    background: red;
    cursor:move;
}

p {
    padding: 0px;
    margin: 0px;
    outline-style: dotted;
    outline-color: #000;
    outline-width: 1px;
}

Some example HTML:

<p class="drag bound square">Thing One</p>
<p class="drag square">Thing Two</p>

Please note I am including the JavaScript so that if I have questions on how things are applied relative to what I’ve written. Also, thank you all for reading and helping. StackOverflow has been an exceptional resource in learning how to code in JavaScript.

EDIT:

1) I should say that I am coding the engine to help me learn the language. This is my first week of JavaScript, and I would like to be able to code in the language before I use a library.

2) For example I would really like for someone to explain how offsets are working here. I would like to know how instead of using position:absolute to make my JavaScript engine, I can use position:relative so that elements can stack on top of each other ect.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-20T08:30:47+00:00Added an answer on May 20, 2026 at 8:30 am

    I’ve posted a solution at http://jsfiddle.net/vJ6r6/.

    First of all, I nested the items to be dragged inside the bounding box:

    <div class="bound">Thing One
        <div class="drag square">Thing Two</div>
        <div class="drag square">Thing Three</div>
    </div>
    

    Also, I turned them into div’s because p’s can’t be nested. (Don’t forget to change the style declaration as well.)

    Then, I set styles on the bounding box:

    <style>
    .bound {
        margin: 100px;
        width: 400px;
        height: 400px;
        position: relative;
    }
    </style>
    

    The key property is position: relative, which causes the items inside it to be positioned relative to it, rather than to the page. Note that because I’m using relative positioning, this example works best when you want to keep the items in a particular container.

    My changes to the JavaScript were more radical, so here’s the whole thing:

    <script>
    var dragInfo;
    
    function down(event) {
        if (~event.target.className.search(/drag/)) {
            document.addEventListener("mouseup", drop, false);
            var t = event.target;
            t.style.zIndex = 100;
            dragInfo = {
                element: t,
                // record the bounds
                maxX: t.parentNode.offsetWidth - t.offsetWidth,
                maxY: t.parentNode.offsetHeight - t.offsetHeight,
                // we don't need findPos, because it's no longer relative to the page
                posX: event.clientX - t.offsetLeft,
                posY: event.clientY - t.offsetTop
            };
            document.addEventListener("mousemove", freeMovement, false);
        }
    }
    
    function freeMovement(event) {
        // the min and max calculations keep the X and Y within the bounds
        dragInfo.element.style.left = Math.max(0, Math.min(event.clientX - dragInfo.posX, dragInfo.maxX)) + "px";
        dragInfo.element.style.top = Math.max(0, Math.min(event.clientY - dragInfo.posY, dragInfo.maxY)) + "px";
    }
    
    function drop() {
        dragInfo.element.style.zIndex = 1;
        document.removeEventListener("mousemove", freeMovement, false);
        document.removeEventListener("mouseup", drop, false);
    }
    
    document.addEventListener("mousedown", down, false);
    </script>
    

    Note that this line:

    dragInfo.element.style.left = Math.max(0, Math.min(event.clientX - dragInfo.posX, dragInfo.maxX)) + 'px';
    

    Is equivalent to this:

    var x = event.clientX - dragInfo.posX;
    if (x < 0) x = 0;
    if (x > dragInfo.maxX) x = dragInfo.maxX;
    dragInfo.element.style.left = x + 'px';
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I am trying to understand how to use SyndicationItem to display feed which is
this is what i have right now Drawing an RSS feed into the php,
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
Basically, what I'm trying to create is a page of div tags, each has
link Im having trouble converting the html entites into html characters, (&# 8217;) i
I am trying to loop through a bunch of documents I have to put
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm new to using the Perl treebuilder module for HTML parsing and can't figure
Seemingly simple, but I cannot find anything relevant on the web. What is the
Does anyone know how can I replace this 2 symbol below from the string

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.