Hacker News new | past | comments | ask | show | jobs | submit login
[dupe] Dragula: Drag and drop so simple it hurts (github.com/bevacqua)
307 points by bevacqua on Feb 5, 2016 | hide | past | favorite | 104 comments



With that name, the motto should be "Drag and drop that's not a pain in the neck".


That motto, plus its fantastic logo, would make it by far the best branding of any open-source plugin.


I was always a fan of HammerJS's branding, but it looks like they removed the silhouette of MC Hammer from their front page :( http://hammerjs.github.io/


Winner!


On a slightly different note - have you ever wanted to click/tap to rearrange elements on -any- website?

Just yesterday I wrote a little bit of JavaScript that will let you reposition any element by dragging it: http://codepen.io/tomhodgins/pen/LGJKdE

And of course, I also minified it so it can be used from the address bar or as a bookmarklet. The minified version is at http://staticresource.com/dragon.js

Ive been having fun loading up sites I know, invoking the JS and then trying to rearrage the elements into better designs! For example, how would HN look if the reply buttons were aligned to the right edge of the textarea they are under, that would be an improvement :) We can try it out!


This looks like a fun experiment. Have you considered adding this as a Chrome plugin and make it "remember" what you drag? Also maybe implement some sort of "undo" mechanism as well?

Thanks for sharing.


Hi! Thanks for your interest.

> Have I considered making it a chrome plugin?

No, but you can run it by pasting 'javascript:' in the URL bar, followed by the contents of http://staticresource.com/dragon.js or as a bookmarklet in Chrome, but the real intended browser I was hoping to use this on was Mobile Safari - to rearrange sites via touch on limited hardware. It also works flawlessly on a $50 Amazon Fire tablet too!

What I created it for was the ability to load up a site, rearrange it, screenshot it - and refresh to have it return to normal (either for more screenshots or to use it). One reason this won't do what you're thinking it will 'saving the location to where you have dragged it' is that it does unexpected things when you resize the browser. If your browser always remembered where you positioned things I think it would quickly end up broken :/

> Can you implement an undo?

I was thinking about this last night. It is possible (you could remember the previous values for the top and left, then set those values when a keyboard key is pressed) but again the big target for this script for my use will be browsers without keyboard (for an undo shortcut) so I'd also need to add an on-screen undo button. I'm still thinking about this and how to accomplish it.

Feel free to use the source as well, consider it under MIT license :)


Please add a trash can in the corner so you can throw out any element you don't like!

Once I ran an X window manager on XCalc's client window. Each button got its own window frame, and you could move them around and iconify the ones you didn't need. Unfortunately the icons were bigger than the buttons.


Did you know in the developer tools (if you right click on an element and hit 'Inspect') if you have an element selected in the live DOM tree view you can hit delete or backspace (can't remember) and actually just delete that node from the rendered page!

If you want to cosmetically hide it without deleting it, you can click in the sidebar where there are all of the CSS styles there that apply to the element you have selected you can add (double click at the top of the sidebar and start a new rule)

    display: none
And the element will visually be hidden, while that content is still on the page in a hidden way.

What you would find, if I tried to add an 'X' button to every element on the page, is that often things are in multiple containers - and the most broken sites are usually the ones with the biggest HTML. It would be nearly impossible for you to 'X' out of elements visually top-down, the only way I can see you being able to get in and actually select which element to delete is using the tree-view in inspect element where you can navigate through the elements in the stack as though you're looking from the side and can touch just the layer you want.


Excellent story, but I assume few applications these days use Xt or Xaw widgets anymore.

It's striking how the pendulum has swung away from programmer-orientated environments like X11 or Emacs where writing your own policy/component/tool/script is encouraged and attributes of internal widgets etc. are accessible. May it swing back soon.


This is really cool.

I could totally see a visual web editor that could work by dragging things around like this, with the css properties in a sidebar updating as you drag things around. And it could also work for "power users" by letting you edit the css directly, like you would in the browser Inspector.

I myself like to design in the browser to quickly see changes but sometimes Inspect element > Manually track and copy all changes to actual editor gets a little annoying.

Would love to use what I just described.


My job is to design sites that work responsively, from widths randing from 200px - 2000px. There's no way one layout that could be achieved through drag-and-drop like this could adapt to fit desktop, tablet, and phone users, unless you have multiple, entirely different layouts built for different widths using the same elements, so then it 'jumps' between totally different layouts between phone, tablet, and desktop. That's not ideal since desktop users may resize their browser into 'tablet' mode and totally lose the experience. Jumping between alternate layouts is jarring.

The nature of responsive CSS is that the simplest way to build a responsive website isn't to use a tool - but just to write the CSS by hand. I don't even use SASS or Less to compile CSS for me. At the end of the day, if the result you want is lines of CSS in a file, the simplest way to arrive at that result is to write only the lines of CSS you need.

If you're wanting to design responsive websites I'd say the easiest tool to use would be a text editor!


I agree, I only work with hand crafted artisanal css harvested from the finest css trees in the highlands of Discordia.


If CSS is written properly it can cascade! I think some people enjoy doing more work than they need because sometimes it adds fun or makes their particular job on a team less intense. But I get paid based on how much work I am able to do, so getting things done as directly and pragmatically as possible benefits me the most.

You can also use some expressions to match selectors in CSS, for example I use `.float-none`, `.float-left`, and `.float-right` as class names for my basic image floats. I can select all images with these classes applied with `img[class^="float-"]` and I can catch individual classes with `.float-left` or something like `img[class*="-right"]`. I think people would sooner learn and use tools that promise to make CSS easy, instead of advancing their CSS skills.

Check out http://elementqueries.com for some of the crazy fun stuff you can do with CSS by extending the language with a little JS. I'd sooner write styles like this that let you reduce the amount of HTML and CSS you have to write than to start introducing extra steps and tools between my files and the browser that multiply the amount of HTML and CSS being output before I can see the result.

I do also author and publish my own CSS stylesheets and plugins that can be used in other sites, so pretty quickly I can bring good CSS into any codebase to fix most common problems.


No no, of course. I agree that typing css is still the best way.

I just meant that moving things around and seeing the CSS change accordingly would be an educating "bonus" tool for beginners within what would be a fully fledged "live view" editor for people like you or me.


I only use Firefox for testing, not as my primary development browser - but they do have a number of visual editing tools built into Firefox Developer Edition that may fit the bill for desktop users!

https://www.mozilla.org/en-US/firefox/developer


You can actually, I've done it before. Just have your drag and drop logic work in percentages of containers, instead of pixels.


Got any examples? You're not going to come up with a design like my examples through any kind of a visual editor that didn't already have code specifically pre-written for this sort of responsive interactivity. Try resizing these from phone width to desktop width to see how the content adapts responsively:

- http://elementqueries.com/demos/pricing-chart.html

- http://elementqueries.com/demos/content-blocks.html

- http://staticresource.com/modals.html

- http://elementqueries.com/demos/testimonial.html


This has a lot of potential to be very useful. One suggestion I'd make (or just implement myself) is suppress mouse events. When I'm dragging a link, for example, and I release the mouse it counts as a click on the link and I lose everything I moved.

The biggest use case I see for this is making super fast screenshots of variations of pages to illustrate an idea for an improvement to developers, other designers, or stakeholders.


There is already `e.preventDefault()` happening on the events, so for example when you drag on a touchscreen it would normally scroll the page - but after invoking this it won't do that.

What I'm not sure how to do is block other things on the page specifically also set to happen on the same events.

On a desktop web browser playing around with this I've had success hammering on the Esc key while moving links though. If you press Esc right after releasing most links it won't leave the page :)


I managed to alleviate most of the problem by adding a new click event listener that `e.preventDefault()` to every target of the drag event. It's kinda clunky but it works for anchor tags. Doesn't work if the element uses JS for navigation/showing a modal/etc.

I figure effectively disabling everything you drag doesn't really matter as dragging stuff around kinda FUBARs the page anyway.



There were many more than that: https://hn.algolia.com/?query=Dragula&sort=byDate&dateRange=.... It's of course fine to submit your own work to HN—more than fine, it's encouraged—and a small number of reposts are ok if a story hasn't had significant attention in the last year or so (see https://news.ycombinator.com/newsfaq.html), though a dozen is excessive.

More importantly, though, this submission has received significant attention on HN within the last year: https://news.ycombinator.com/item?id=9914045. That makes this post unequivocally a dupe.

It's obviously a good project and there are many people in the thread learning about it for the first time and finding it interesting, which is great. But 300 points 7 months ago is so obviously within the dupe window that I think justice has to trump mercy in this case, though our bias runs the other way.

The underlying problem is that so much good stuff streams through HN that nobody can see more than a fraction of it.


To me, it looks like a project worth believing in, despite what might be considered to be a substantial lack of glamour. Perhaps, one way of looking at it is that the author knew it was right and useful and pushed the rules...incidentally, the sort of rules where nobody is going to get hurt.

To put it another way, I suspect that submitting the same thing about once a month or so, is line noise when it comes to spamming Hacker News. And if the content were bad it probably would have been flagged to death at least once. It hasn't been, because it's good but unnoticed.

It could be it went rather unnoticed because each submission wasn't tweeted to a bunch of friends for upvotes, it never was submitted to product hunt, and the author doesn't search engine optimize on Medium.

And anyway, as this comment by me illustrates, meta discussion is often dull. Hence, generally discouraged by Hacker News Guidelines.


I'm sincerely glad it was submitted that often, otherwise I might not have seen it today.


Absolutely. To quote a fictional Charles Manson quoting 1990s UPN, "If I haven't seen it, it's new to me!" I'm probably going to replace our existing drag/drop solution at work with Dragula since it is much superior, but if this wasn't posted today I would not have even thought to even look for it.


Quoting Family Guy and Charles Manson in the same sentence should be grounds for a state sponsored lobotomy.


Yes. It clearly has value and I'm glad people got to see it too. Unfortunately, this is a tradeoff with no satisfying optimum.


Glad to see it has garnered a little more discussion / visibility this time. I'm glad to have found it :)


I for one am happy it got posted again - looks like a quality JS component I have not seen before.


I wonder how it go submitted so many times in the last 6 months (clicking the "past" link by the link to the article makes it obvious). Isn't the duplicate detection supposed to stop that?


> Isn't the duplicate detection supposed to stop that?

This may be entirely made up, but I remember hearing that the duplication detection doesn't apply if a submission doesn't get a certain amount of attention. Looks like the only submission to get more than 3 points was 297 days ago.


You were wrong on the facts (see https://news.ycombinator.com/item?id=9914045, though there were so many it's easy to miss the big one), but right on the policy: not only did you not make it up, it's in the FAQ! Linked at bottom of every page.


> but right on the policy: not only did you not make it up, it's in the FAQ! Linked at bottom of every page.

Haha, my bad! I actually did try to search around for it, but it didn't occur to me to check the FAQ. I even checked the github mirror of the code [0] (no idea how up-to-date it is), but I can't read Arc very well. It just goes to show you could probably plaster rules like that as a header over the entire website and people like myself would still look in the wrong place :P

I have read the FAQ before, so that's probably where I "heard it", but I didn't think to check it this time.

[0] https://github.com/wting/hackernews


> you could probably plaster rules like that as a header over the entire website and people like myself would still look in the wrong place

That's very true. I even alluded to that in my comment but took it out as off-topic. It isn't you, though, it's everybody. Disseminating knowledge to the community is hard.


Yes. And some of these other positive comments around here are very suspicious.


Many of the positive comments are from other long time members of the Hacker News community...there's not a lot of green on this page.


Where's the harm? It's not a commercial product.


Wow, that's some pretty blatant self-promotion.


HN has traditionally been full of self-promotion, in both submitted links and especially in comments (e.g., lots of "disclosure, I made X" or "shameless plug, I made X" or ...). It's not necessarily a bad thing since the community ultimately has control over what gets seen on top. And additionally sometimes you are your only advertiser.

(In this very comments page, people are talking about their own code they wrote with links to it, etc.)


> HN has traditionally been full of self-promotion...

Yes, but there are rules, and we all should play by the same rules. HNs rules state that if your story got significant attention recently (this story was 1st six months ago) it'll be killed as dupe. But the user has been sending it w/o stop even after that...

>Are reposts ok?

If a story has had significant attention in the last year or so, we kill reposts as duplicates. If not, a small number of reposts is ok.

https://news.ycombinator.com/newsfaq.html


"significant attention" is of course hard to define, but a max. of 3 scores does not count as significant attention in any book I know.



> got significant attention recently ...

I did not include the one submission with >300 because 200 days is not "recently" imho.


I see. But for HN the dispositive time window is a year, as described at https://news.ycombinator.com/newsfaq.html. I don't know when pg came up with that but it was long before I started working on HN.


I think that is a very good thing, I want to know about these useful projects


This is exactly what I was looking for this morning, and am extremely happy that it was posted on HN.


I have no earthly need for this whatsoever--is drag-and-drop ever needed for webapps?--but as an example of clever Javascript code, it's very cool. (Running Firefox beta on Android.)


Another way to look at it is a sign that HN doesn't always bubble quality to the top. HN might not actually care, casualties may be expected as the algorithm's goal is not "all quality rises" but rather "no cruft rises"

Which is fine, but a side effect is people resubmit often hoping one submission will catch.


Most people are irrationally timid about a little bit of self-promotion and err on the comfortable, meek side of doing nothing at all.


I know it's not 'cool' but the fact that this supports IE7+ makes it infinitely more useful to me personally.

Looks very very nice after a short play with the demo!


From the documentation: "You shouldn't include it in the <head> of your web applications. It's bad practice to place scripts in the <head>, and as such dragula makes no effort to support this use case."

Serious question: With nearly 20 years in JS development, the concept of placing scripts not in the head section as being desirable is new to me. (Just saying, it used to be the other way round. Common resources, like scripts were, aside from the title, the main reason, the head tag was introduced at all.) -- Is there a source to this notion of script embedding, or can anyone clarify? (What would be the winning propositions of not using parallel loading slots?)


If you have javascript in the head loading synchronously the page can't even begin to render until the javascript has loaded. Placing script tags at the bottom of the body allows the page to begin rendering while scripts are loading.


There's this facility called slots, at least this is, how it used to be. A resource to be loaded is assigned a slot as available (generally 8 or so) and the browser advances over resource tags. If a resource in the head section is going to be interpreted and is ready, the resource is processed, the slot is freed and available for further jobs. (This is partly, why only hard coded resources are of relevance for the document.DOMContentLoaded event.) There's no connection between single threaded execution and parallel slots.

(Edit: So this may be true for scripts that are requiring further resources, but there's no need for this with scripts that are completely self-contained, like dragula claims to be. Here, this might rather slow down the completion of the page.)


> There's no connection between single threaded execution and parallel slots

It has more to do w/ the DOM rendering. The rendering engine is required to wait for a javascript resource to download because it can't know in advance that the js file won't call `document.write`

`document.write` has a nasty property that it calls `document.open()` if the document is not open for writing (which clears the document). Before the DOMContentReady event, the document is open for writing (this is why, among other things, console.log(document.body) yields null and `document.write("<title>foo</title>") sets document.title` when called from <head>)

If parsing of the document was allowed to skip a js file until it downloaded, and if the script has a `document.write` call, then running the script upon download completion (which would typically happen much later than DOMContentReady fired) would trigger the implicit document.open() call, thus yielding different (and catastrophic) semantics.


What you're describing is the now ancient document stream model (document.open – document.write – document.close; calling document.open() after document.close implies document.open() and a loss of the content by an implied call to document.clear()). But I honestly hope, document.write() isn't used today (quite like "eval"), and everyone uses document.createElement(), etc.

As for the rendering engine having to wait for the resource as it hits it, this is exactly why you want it to be ready then, as opposed to just starting to download it and wait. (Even, if it is the very last tag, it will defer completion. And if every library were claiming to be the last one ...)

> If parsing of the document was allowed to skip a js file until it downloaded (…) – This is, what the "defer" and the "async" attributes are for. (And, again, you don't want to call document.open(), be it explicitly or implied, because you would lose any content there is, since it implies "document.clear()". This is Netscape Navigator 2.0 stuff, 1996, really.)

P.S.: What you're heading for, were mere work-arounds in times, when the document-object would have been created only as the parser hit the <body>–tag (up to and including Netscape 3) and when enumerated properties became available only after the body was opened (Netscape 4, etc). But even then, you would apologize in a comment, if such means were required. (E.g., while addressing Netscape 4's document.layers object in 1997.) Now, that there are so many means to do this appropriately, I see no reason at all of banning common resources from the head section and spreading them over the document.body.


If browsers decided to remove document.write and friends, then they would obtain a guarantee that running a script after the recursive DOM assembly routine yields the same result as running the script synchronously within it (regardless of what the script might potentially do), and they would be able to optimize the pipeline to allow you to put scripts in head without triggering a performance problem.

As far as usage in the wild goes, I've seen document-stream-related functions in rich text editors and comet (old school "websocket polyfills") codebases, but that was many years ago. I can't say for certain why browsers still support those functions.


I would say the best practise for modern browsers is to place this in the <head>:

    <script async src="script.js"></script>


Script tags at the bottom of body has become the accepted standard for faster page loads. I'd think the library would have to be doing some strange things to not work if placed in the head, though.


> I'd think the library would have to be doing some strange things to not work if placed in the head, though.

Not really. All it does is `var body = document.body` in an IIFE. In <head>, that yields undefined.


Why not use document.DOMContentLoaded ?


Embedding scripts in <head> is an established worst practice. It blocks rendering for no good reason. Sum that with the fact that dragula is a drag&drop library and as such you don't need it in the slightest to display your content, and it becomes obvious why I don't support <head> embedding.


Wouldn't a "defer" attribute and waiting for document.DOMContentLoaded be the appropriate way to do this? This would also document the reasons for this and would allow for a decent organization of the document (what the head section is good for). – To me, this is rather late-1990s style, before there were such things as defer and sophisticated DOM events.


That's interesting—I started learning JS last year and I was told to never put it in `<head>` but instead before the end of `<body>`.


Very interesting. I suppose, in fact this would be rather slowing down the page in most cases, if applied as a common rule. That is, provided you were using self-contained inline-resources only. Using any kind of include/require mechanism would change the picture in favor of a touch-as-late-as-possible strategy.


Very nice. Just lightweight js and it seems to work great.

I was going to download it and found:

If you're not using either package manager, you can use dragula by downloading the files in the dist folder. We strongly suggest using npm, though.

Why would they strongly suggest installing npm? (obviously I don't use node)


Because of updates and convenience. You could always use bower or the CDN alternatively. But since npm is the way I use most of the stuff I develop, that's what I recommend. You don't have to use node to use npm, but as a package manager it resolves lots of issues even for front-end components.


npm because it's now the de facto package manager for javascript.

And why a package manager? For many reasons, the most useful ones are :

- ease of install

- you can declare dependencies for your plugin instead of having the end user go to X differents pages to download everything needed

- the most important one : you don't have to check all your packages for important updates like security ones


Is it as powerful as XView drag-n-drop under X-Windows?

http://www.art.net/~hopkins/Don/unix-haters/x-windows/disast...

The "drag-and-drop" metaphor tires to cover up the Unix file system, but so little of Unix is designed for the desktop metaphor that it's just one kludge on top of another with little holes and sharp edges popping up everywhere. Maybe the "sag-and-drop" metaphor is more appropriate for such ineffective and unreliable performance.

A shining example is Sun's Open Windows File Manager, which goes out of its way to display ore dump files as cute little red bomb icons. When you double-click on the bomb, it runs a text editor on the core dump. Harmless, but not very useful. But if you intuitively drag and drop the bomb on the DBX Debugger Tool, it does exactly what you'd expect if you were a terrorist: it ties the entire system up, as the core dump (including a huge unmapped gap of zeros) is pumped through the server and into the debugger text window, which inflates to the maximum capacity of swap space, then violently explodes, dumping an even bigger core file in place of your original one, filling up the entire file system, overwhelming the file server, and taking out the File Manager with shrapnel. (This bug has since been fixed.)

But that's not all: the File Manager puts even more power at your fingertips if you run it as root! When you drag and drop a directory onto itself, it beeps and prints "rename: invalid argument" at the bottom of the window, then instantly deletes the entire directory trwe without bothering to update the graphical directory browser.


What does any of this have to do with Dragula?


Talking about drag-and-drop in a thread about a drag-and-drop library is surely on topic.


coughcoughpiemenuscough



Ah neat. Bevacqua does some great work. If you're interested in JS, browse his github repos and check out ponyfoo.com


Very nice. I once made a shipping planner in X that worked with drag and drop: It was basically a packing game with orders and trucks. You drag the day's orders around to arrange them on the trucks as you like (also you can drag the trucks around, and each truck was a list of orders with a scroll bar). Each truck shows its current capacity and turns red if the capacity is exceeded. Each order shows its delivery address and size (plus you can click on it to view the whole thing). When you are done, you click a button to print the pull tickets, bills of lading and delivery tickets all in the right order. The shipping guys loved it.

(Yes, you could try to use an optimization algorithm to do this- at the time I had no access to the map information needed for it. Actually it would have been difficult to beat the shipper's knowledge anyway.)

Were I to make this app again, I would want drag and drop in a web application. I'm not sure if Dragula allows dragging between frames (and dragging frames themselves).


I'm enjoying playing with this. The only bit so far that I don't like is that to trigger a switch, the mouse needs to cross the halfway point of the element you want to swap positions with: in my application, it would be much more intuitive for an element being dragged to "claim" a drop-target as soon as the mouse moves over the target. I haven't yet found a way to accomplish this with Dragula.


Actually I've gone ahead and worked on it myself, in order to make it compatible with a grid layout (which was the more general problem I was trying to solve).

I still need to clean up my modifications, but I should have a pull-request out within the next day or two, adding 'grid' to the existing 'horizontal' and 'vertical' direction options :)


> Framework support includes vanilla JavaScript, Angular, and React.

Any reason why jQuery isn't on this list?


If there's a vanilla JS version already why would you need it to use jQuery? Wouldn't that be introducing a new 'single point of failure' into this code on your page? If there's any problem with jQuery or jQuery on your page then this code would then also be vulnerable. As-is it's good to go :)


Haven't tried it yet, but I just wanted to comment that the logo and the name are just perfect!


I tried this project recently. I don't have good reviews. Unbinding the drag / drop and re-binding was such a pain I gave up and went to SortableJS, which is very simple to use.


What's the point of sending this again?

https://news.ycombinator.com/item?id=9914045

I thought this was considered spammy behaviour: https://hn.algolia.com/?query=dragula&sort=byPopularity&pref...

I'm not saying that the lib isn't great.


One point of sending this again is that I didn't see it 200 days ago. This is awesome and I'm glad it was submitted again. I'm gonna use this in the future!


We all miss many stories, but HN's rules are quite clear about reposts:

>Are reposts ok?

If a story has had significant attention in the last year or so, we kill reposts as duplicates. If not, a small number of reposts is ok.

https://news.ycombinator.com/newsfaq.html

I've seen this story at least 3 times in the last months both on new & 1st place in the front page sections:

https://hn.algolia.com/?query=dragula&sort=byPopularity&pref...


Only one of posts got any attention and it was 7 months ago. I hardly call that "significant attention". Which, by the way, is completely subjective and thus the opposite of "quite clear".


The same user has been posting this multiple times a month, almost every month. Now that this entry got attention, I hope he stops, although his first post got very signification attention and it hasn't even been a year.


Don't you have better things to do than worry about this?


That's not nice. The fact that users worry about HN being good is the most important thing keeping it good.


The time window we apply is "about a year", and 300+ points is clearly significant, so by HN's longstanding policy there's no question that this is a dupe.

https://news.ycombinator.com/newsfaq.html


It's probably better to discuss issues regarding the mechanics of Hacker News via email with dang because ordinary users can't change them and meta discussions are discouraged by the community.


I've just emailed dang, hopefully someone from the HN team can clarify where is the red line...


Pretty rad, however the issue I see using this on mobile, is that the act of scrolling the page, moves elements around.


Upvoted primarily for the repo name.


Mmmh no CDN? I wanted to quickly try it on jQuery but couldn't



It will be super cool with resizable functionality


Can this be used in a Rails project?


Demo works on mobile well. Nice.


Nice logo


Can you dig trough the ditches and burn trough the witches with it?


Build is failing now.


tldr: seems to be some browser thing.


[deleted]


I actually thought it was quite clever


I think their choice of font is poor due to the kerning of the "gu" in "ragula", but I think the "D" stylization is extremely impressive. Whoever came up with that is very talented.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: