Solved

Create a div by dragging

Posted on 2013-02-03
14
261 Views
Last Modified: 2013-02-05
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
0
Comment
Question by:steva
  • 5
  • 5
  • 4
14 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 38849160
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
 
LVL 16

Assisted Solution

by:Steve Krile
Steve Krile earned 250 total points
ID: 38849198
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
 

Author Comment

by:steva
ID: 38849403
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
 
LVL 16

Expert Comment

by:Steve Krile
ID: 38849415
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
 
LVL 82

Expert Comment

by:leakim971
ID: 38849420
try from right top corner
to lower left

:))
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 250 total points
ID: 38849449
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
 

Author Closing Comment

by:steva
ID: 38849506
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
What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
LVL 82

Expert Comment

by:leakim971
ID: 38849601
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
 
LVL 16

Expert Comment

by:Steve Krile
ID: 38850770
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
 

Author Comment

by:steva
ID: 38850944
Thanks skrile.  I just ordered Bernard's "KnockoutJS Starter."   I hadn't heard of KnockoutJS.

Steve
0
 
LVL 16

Expert Comment

by:Steve Krile
ID: 38851005
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
 

Author Comment

by:steva
ID: 38853933
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
 
LVL 16

Expert Comment

by:Steve Krile
ID: 38854643
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
 

Author Comment

by:steva
ID: 38856465
Thank you!
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now