Create a div by dragging

Has anyone seen a jQuery (or YUI) module that lets you insert a DIV into a window by clicking where you want the upper left corner and then dragging to where you want  the lower right corner, and releasing?

Thanks
stevaAsked:
Who is Participating?
 
leakim971Connect With a Mentor PluritechnicianCommented:
check this one : http://jsfiddle.net/hcAcy/1/

YUI().use('event', 'node', function (Y) {

    Y.one("document").on("mousedown", function(evt) {
        var div = Y.Node.create("<div class='newDiv' data-left='" + evt.pageX + "' data-top='" + evt.pageY + "' style='position:absolute;left:" + evt.pageX + "px;top:" + evt.pageY + "px;background-color:blue'></div>");
        evt.target.append(div);
    })
    Y.one("document").on(["mouseup", "mousemove"], function(evt) {
        var div = Y.one("div.newDiv");
        if(div) {
            var orgX = div.getData("left");
            var orgY = div.getData("top");
            var width = orgX - evt.pageX;
            var height = orgY - evt.pageY;
            if(width>0) orgX = evt.pageX;
            if(height>0) orgY = evt.pageY;
            div.setStyles({"width":Math.abs(width)+"px", "height":Math.abs(height)+"px", "left":orgX+"px", "top":orgY+"px"})
            if(evt.type=="mouseup") div.set("className", "");
        }
    })
    
});

Open in new window

0
 
leakim971PluritechnicianCommented:
test page : http://jsfiddle.net/hcAcy/
YUI().use('event', 'node', function (Y) {

    Y.one("document").on("mousedown", function(evt) {
        var div = Y.Node.create("<div class='newDiv' data-left='" + evt.pageX + "' style='position:absolute;left:" + evt.pageX + "px;top:" + evt.pageY + "px;background-color:blue'></div>");
        evt.target.append(div);
    })
    Y.one("document").on(["mouseup", "mousemove"], function(evt) {
        var div = Y.one("div.newDiv");
        if(div) {
            var width = div.getData("left") - evt.pageX;
            var height =  evt.pageY - parseInt(div.getStyle("top"), 10);
            div.setStyles({"width":width+"px", "height":height+"px", "left":evt.pageX+"px"})
            if(evt.type=="mouseup") div.set("className", "");
        }
    })
    
});

Open in new window

0
 
Steve KrileConnect With a Mentor Commented:
I hunted around a bit and didn't find anything.  But this little mock-up might get you pushed in the right direction.

<!DOCTYPE html>
<head>
    <title>Drag Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

<style type="text/css">
	body {width:100%;padding:0;margin:0;font-family:"Arial";
         -webkit-user-select: none;
        -khtml-user-select: none;
        -moz-user-select: none;
        -ms-user-select: none;
        -o-user-select: none;
        user-select: none;

	}
    .content
    {
        height:400px;
        width: 400px;
        margin:20px;
        border:solid 1px #ccc;
        position:relative;
    }

    .dragging
    {
        cursor:crosshair;
    }

    .dragbox {position:absolute;opacity:0.5;background:#eee;border:solid 1px #aaa;}
</style>

<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>

<script type="text/javascript">
    $(document).ready(function () {
        $(".content").mousedown(function (e) {
            var parentOffset = $(this).parent().offset();

            //change the pointer
            $(this).addClass("dragging");

            //starting point of the box
            var relX = e.pageX - parentOffset.left;
            var relY = e.pageY - parentOffset.top;

            //add the drag box
            var div = $("<div class=\"dragbox live\" />").css({ height: "10px", width: "10px", top: relY-12, left: relX-32 });
            $(this).append(div);

            $("#xoffset").text(relX);

        }).mousemove(function (e) {
            var parentOffset = $(this).parent().offset();
            //current location of the mouse cursor
            var relX = e.pageX - parentOffset.left;
            var relY = e.pageY - parentOffset.top;

            //get the box that is being drawn
            var div = $(this).find(".live");
            if (div.length != 0) {
                var boxPosition = div.position();

                var newY = relY - boxPosition.top;
                var newX = relX - boxPosition.left - 22;

                div.css({ height: "+" + newY + "px", width: "+" + newX + "px" });

            }

        }).mouseup(function(){
            //get the live box
            var div = $(this).find(".live");
            //remove the live designation
            div.removeClass("live");

            //turn off the crosshairs
            $(this).removeClass("dragging");
        });
    });
</script>
</head>

<body>
	<div class="content">

	</div>
</body>

Open in new window


Here's a fiddle: http://jsfiddle.net/skrile/jZxgz/
0
Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

 
stevaAuthor Commented:
Thanks guys!

Leakim, I was expecting to be able to create the div in the Result panel of your fiddle by dragging, but nothing happens.  

And skrile, I was able to create the div in your fiddle, but was expecting the created div to show up in the HTML panel.

What am I missing?

Thanks again for the solutions.

Steve
0
 
Steve KrileCommented:
The element is being added to the DOM directly, so it won't show up in the jFiddle's HTML pane.  If you were to run the code from a stand-alone page (from my CODE block) you should be able to inspect the HTML and see the added element.
0
 
leakim971PluritechnicianCommented:
try from right top corner
to lower left

:))
0
 
stevaAuthor Commented:
Thanks a million, both of you!

Leakim,

You seem to prefer  YUI to jQuery, and I notice that your solution is about half as long as skrile's jQuery solution.  Do you think YUI3 is a superior framework?

Steve
0
 
leakim971PluritechnicianCommented:
Mercedes or BMW? Crayons or markers? :))

I think you need to have more programming knowledge to code with YUI3, it look for me nearer simple javascript..

You need to know where you're going and check widgets or plugins availables to choose
Today we should compare jQuery UI with YUI3
I don't think one is superior to the other

The same code with jQuery : http://jsfiddle.net/hcAcy/2/
The YUI3 corrected : http://jsfiddle.net/hcAcy/4/
0
 
Steve KrileCommented:
FWIW I almost never use Jquery directly any longer.  I do use jQuery UI - but that's mostly set it and forget it.  

Most of my DOM manipulation now is handled by KnockoutJS given that most of my projects are web applications rather than "presentation" sites.
0
 
stevaAuthor Commented:
Thanks skrile.  I just ordered Bernard's "KnockoutJS Starter."   I hadn't heard of KnockoutJS.

Steve
0
 
Steve KrileCommented:
The curve for learning Knockout is a bit steep (at least for me it was).  It took me about 6 months to feel like I knew what was going on and another 6 months to get good at it.  But now - it is a default include in all of my projects.  It removes a lot of the hassles you think of when dealing with painting data on a screen.
0
 
stevaAuthor Commented:
skrile,

You said,
Most of my DOM manipulation now is handled by KnockoutJS given that most of my projects are web applications rather than "presentation" sites.

I'm sure I'm being naive here and I'm hoping to learn something,  but to my thinking it seems that DOM manipulation, wherever it occurs, has one purpose,  to makes neat things happen on the screen when the uses clicks something. So I'm having a hard time imagining what DOM manipulation would be doing in a web application. I'm sure this is my ignorance, but could you possibly say a few words about how your web applications benefit from DOM manipulation?  

Thanks for anything you care to share,
Steve
0
 
Steve KrileCommented:
If you are even a little interested, check out the online learning site for Knockout.  It's fantastic.

One thing to think about is how you get and display your data.  I NEVER use server-side data display tools anymore.  Everything I work on now is done through services.  If I want a table of data, I load the page first then make my call for the data.  This allows me to make a call for that data whenever I want rather than being tied to post-backs.

The rabbit hole is truly very deep - but here is a simple example illustrating how beautiful and jquery free knockout can be.  Notice this example DOES NOT include jquery - although as a practical matter I do indeed use jquery from time to time.

<!DOCTYPE html>
<html>
<head>
    <title>Knockout Sample</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />

    <style type="text/css">
	    body {width:100%;padding:0;margin:0;font-family:"Arial";}
    </style>
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/knockout/knockout-2.2.1.js"></script>

</head>

<body>
	<div class="content">
        <ul data-bind="foreach: list">
            <li><span data-bind="text: first + ' ' + last"></span> (<span data-bind="text: age"></span>) <a href="#" data-bind="click: $root.showData">Click</a></li>
        </ul>
	</div>
</body>

<script type="text/javascript">
    //base knockout model variable
    var pm = {};

    //add an observable array
    pm.list = ko.observableArray([
        {first: "Jim", last: "Canne", age: 23 },
        {first: "Carolyn", last: "Smith", age: 25 },
        {first: "Alex", last: "Robinson", age: 20 }
    ]);

    //a function to react to the click event
    pm.showData = function (data) { 
        //knockokut click events send the event and data objects as a default.
        alert("You clicked on " + data.first + " " + data.last + " who is " + data.age + " years old.")
        
    };

    ko.applyBindings(pm);
</script>

</html>

Open in new window

0
 
stevaAuthor Commented:
Thank you!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.