Тёмный

How To Build Sortable Drag & Drop With Vanilla Javascript 

Web Dev Simplified
Подписаться 1,6 млн
Просмотров 333 тыс.
50% 1

🚨 IMPORTANT:
1 Year Free Hosting: www.atlantic.n...
Use code KYLE for an additional $50
Drag and drop is something that nearly every web application needs, but it can be tricky to build from scratch. That is why in this video I will be showing you exactly how to build a sortable drag and drop list with very little JavaScript.
📚 Materials/References:
GitHub Code: github.com/Web...
CodePen Code: codepen.io/Web...
Reduce Tutorial: • 8 Must Know JavaScript...
🧠 Concepts Covered:
- HTML drag and drop attributes
- JavaScript drag and drop events
- JavaScript reduce function
🌎 Find Me Here:
My Blog: blog.webdevsim...
My Courses: courses.webdev...
Patreon: / webdevsimplified
Twitter: / devsimplified
Discord: / discord
GitHub: github.com/Web...
CodePen: codepen.io/Web...
#DragAndDrop #WDS #JavaScript

Опубликовано:

 

28 сен 2024

Поделиться:

Ссылка:

Скачать:

Готовим ссылку...

Добавить в:

Мой плейлист
Посмотреть позже
Комментарии : 394   
@mouseclicker4955
@mouseclicker4955 3 года назад
The math was a little difficult for me to understand at first, so I changed the formula a little. Since the y-position increases as you drag the mouse down, I set the offset = y - (box.top + box.height / 2). Since the top of the box's y-coordinate is given to us, all we need to do is add half of the box's height to it and it finds the middle for us. I understand most people might have understood the original equation, but I just wanted to add this here in case anyone was confused.
@먼데이좋은데이
@먼데이좋은데이 2 года назад
the formula is eventually the same, but your explanation is more intuitive. Thanks a lot!
@RobertFletcherOBE
@RobertFletcherOBE 2 года назад
That's because it's needlessly complicated for such a simple problem. just get the element your hovering over using document.elementFromPoint(e.clientX, e.clientY) then check if your mouse is in the upper or lower half of the elements rect. Its the only part of an otherwise good tutorial that just seemed to be there for the sake of looking fancy
@AndrewTSq
@AndrewTSq Год назад
@@RobertFletcherOBE I've been doing HTML for 2 years, and its first time I hear about this function :D This makes lots of thing way easier. Thanks!.
@AndrewTSq
@AndrewTSq Год назад
@@RobertFletcherOBE i have tried this now, but the problem is when you drag an element and your poinyer is between 2 elements, then it defaults to last in the list, until you go over an element. So it looks kind of bad
@keremardcl6759
@keremardcl6759 Год назад
@@AndrewTSq this is not HTML though :)
@maskman4821
@maskman4821 4 года назад
This is the tutorial I've been waiting for, this is apparently the best drag-and-drop vanilla js tutorial for sure. I have learned a lot. for people who don't want to go deep on technical part, there are a few libraries that simplify the work. But understand how drag and drop works under the hood make developing work more flexible and free. But for people who just want to quickly get started and apply drag-and-drop into their projects then 3rd-party libraries do the work. Anyhow, thank you Mr. Kyle Cook for this tutorial, you seem to know what everybody needs and wants, impressive, amazing and awesome !!!
@vinisha7796
@vinisha7796 2 года назад
what libaries can you use for drag and drop?
@cryptixdaemon7236
@cryptixdaemon7236 18 дней назад
It's necessary to understand what goes on under the hood if you want to know how it works and be able to customize it further.
@cryptixdaemon7236
@cryptixdaemon7236 18 дней назад
Nice tutorial, but it can't scale easily
@beinyourguard
@beinyourguard 4 года назад
you are a very smart programmer, i hope to be like you someday
@mark-dev-1
@mark-dev-1 6 месяцев назад
Damn brother, the way you verbalize as you go, even though you're watching on second screen a finished product, is still amazing.
@vaibhavyadav8726
@vaibhavyadav8726 3 года назад
In the end Kyle said, and that's all there is to creating this "SIMPLE"...
@johnbritolima
@johnbritolima 3 года назад
LOL
@JohnWickXD
@JohnWickXD Год назад
Haha
@memoryleakerz
@memoryleakerz 10 месяцев назад
I think the main key of your videos is that you don't make a whole pretty and solid toturial to be copy pasted from, I literally wanted to learn that API's basics and that exactly what I got with a little be more tips like getting the rect info with that clientBounding function I'm going library-less approach on all of my personal projects as much as possible and wanted to implement this with my own react custom hook for my needs. Much thanks!!!
@tochimclaren
@tochimclaren Месяц назад
This! I'm tired of seeing RU-vid videos where the developer spins up react app to do a simple demo. I'm also using as little library as possible.
@basroos_snafu
@basroos_snafu 4 года назад
Man, your videos are so inspiring. My server side is still classic ASP and I should upgrade to some new language, but your client-side applications are still usable in my situation, and I will definitely implement some of the solutions you provide. I've always managed to solve problems by just using Google and find what's available on the web, but what you teach is complete and solid. Thank you so much for all the effort, although I know it's fun to make. Keep up the good work!
@LawnCrack
@LawnCrack 3 года назад
I don't think I've ever commented on your channel Kyle. Just wanted to say, YOU ARE THE MAN! Love your content. It's all over my head. Exactly what I need!
@abrar8133
@abrar8133 3 года назад
I'm not exaggerating but you have the best channel! I watched so many javascript videos but most of them don't go into clear details just like you do.. THANK YOU
@Snoo29293
@Snoo29293 3 года назад
I had to watch it twice but I finally understood it.
@keremardcl6759
@keremardcl6759 Год назад
holy moly this is a perfect tutorial. Now I need to figure out how to post the index of each element so as to change their priority level in my DB :)
@Adrian-aTak.19
@Adrian-aTak.19 Год назад
i think you can make a column in the db that specify the priority level
@RufusVidS
@RufusVidS 4 года назад
I enjoyed your fast paced tutorial, and I couldn't wait to use arrow-functions as event listeners. DON'T DO THIS! The 'this' parameter is handled differently within arrow functions than simple anonymous functions (which as a noob, took me a while to figure out). You avoided this problem by knowing the event target was the only one with the class 'dragging' and you grab it directly with querySelector(), but a more generic handler might want to use 'this', which in an arrow function would have to be evt.target instead.
@MasterTeeee
@MasterTeeee 2 года назад
This is all very true, and well worth noting. One thing I would say, is that the fact that arrow-functions retain the scope of `this` to be that of the outer scope (rather than the same as the scope of the calling function), is its greatest strength. The old way to get around this was to use the `bind()` function to inform the event callback of what you want `this` to represent within said function. This is a pain in the arse after a while (especially when you're nesting functions within functions, with callbacks and recursion; it quickly becomes a mess of what `this` refers to), and arrow functions were introduced to JavaScript to make everything much clearer (arrow functions also have some awesome shorthand properties, that can make your code much more concise, and therefore quicker to write). This is most noticeable when you're following OO (Object-Oriented) design principles, and have all of these events contained within a class, where you might want to use those instance methods within the event callback, just like you would anywhere else within the class. I think wrapping your head around scopes and sync/async are the two major hurdles when transitioning from beginner JavaScript to intermediate JavaScript, but once you know them inside and out, your programming (both writing/coding and conceptualising) will continue to improve in leaps and bounds!
@AveN7ers
@AveN7ers 2 года назад
Just don't use 'this' . e.target or e.currentTarget do the same thing
@imraff
@imraff 2 года назад
Really amazingly well explained and easy to follow, will definitely be using this in a project at work soon and i was DAUNTING it, thinking it would be super complex/rely on a framework I'm not familiar with but you really broke it down super easily. Can't wait to play with and maybe add x coord too! Thanks again.
@theresacampbell9084
@theresacampbell9084 2 года назад
Your job truly is simplifying the web 👌🏾
@orashusedmund7675
@orashusedmund7675 7 месяцев назад
thank you Kyle, great video, helped me finish a task. 😇
@edenmaimon6983
@edenmaimon6983 2 года назад
Thank you! It was very complicated for me, but you explained it excellently! Starting to follow your channel.
@JonPeppinck
@JonPeppinck 2 года назад
Do any math geniuses / smart people know how to change the formula to make it such that - when you click and drag an item, to be able to still move it if you are hovering over anywhere over the full height of the next element, opposed to the top 50% of the element?
@toonice555
@toonice555 10 месяцев назад
Wow due you figured this out on your own? I wouldn't even know where to start!
@SOUVIK_RAY_
@SOUVIK_RAY_ 4 года назад
This is an awesome tutorial. You have explained really well. It was very easy to implement it in my code with a slight variation.
@rshum85
@rshum85 11 месяцев назад
This helped out with my project, thanks so much!
@brian1801
@brian1801 3 года назад
Quite simply -- YOU ROCK! Great content. Even better presentation. Thanks for making such an awesome video.
@cyphi1
@cyphi1 3 года назад
I have an idea...don't think it'll be simple, but it should be doable with your help!! thanks for the video!!
@mdzafrullahsarafat1409
@mdzafrullahsarafat1409 4 года назад
Great tutorial. I Always learn new things when I watch your tutorial.
@almadev183
@almadev183 3 года назад
Thank you so much... Very useful, I applied an addapted version to my project. Very well explained, definitely I will watch more of your videos.
@mala235813
@mala235813 2 года назад
Perfect tutorial. Big thanks! Just what I needed.
@kennethkuah6645
@kennethkuah6645 3 года назад
How do you make it for left and right as well? If I want to move my elements left and move it right how do I go about doing it?
@Fooljuice
@Fooljuice 3 года назад
This was really helpful. Thanks Kyle.
@uimonk
@uimonk 4 года назад
We would like to know more about you. How you do such difficult task effortlessly?
@thegeeeeeeeeee
@thegeeeeeeeeee Год назад
great video. For new learners like me, it would help if you mention which words are built in to Javascript... (ex: closest/ offset/ y) Thanks for everything m8!
@MrParktesla
@MrParktesla 27 дней назад
Thank you a thousand times :)
@apollossevere1071
@apollossevere1071 2 года назад
This dude is a beast!!!
@ulviugur3605
@ulviugur3605 3 года назад
Vanilla Javascript looks very easy, compared to the React DnD example (was a very nested -> crazy structure). Can one use the JS code in React pages as well ?
@joboujp
@joboujp 7 месяцев назад
Nice tutorial. Do you know a way of keeping the draggable element from leaving the browser window ?
@shibafundamentado1837
@shibafundamentado1837 2 года назад
This my first javascript project,learned a fucking lot with this video.it was chalenging,BTW english is not even my native language.
@denniskim4326
@denniskim4326 4 месяца назад
So is it possible to add x-offset logic to insert a draggable element into a grid-like layout of elements? Excited to go home and try it using this video as a guide. Thanks Kyle!
@WebDevSimplified
@WebDevSimplified 4 месяца назад
Thanks for the support! You could 100% do this with the X direction as well to create a grid of elements and it shouldn't be too much more code.
@ramziaswad3079
@ramziaswad3079 2 года назад
hi Kail .. Can you teach us please how to do employee shift planning using js and jquery? there is no youtube video explaining it !! Thanks
@RickyTanTriads
@RickyTanTriads 2 года назад
How would you save the position of the draggable elements in local storage?
@ouwedouwe
@ouwedouwe 2 года назад
How would i check if there is already an draggable in the container?
@abhijeetsingh1387
@abhijeetsingh1387 4 года назад
Thank you for this one! This is a really useful tool!
@budkin
@budkin 4 года назад
Fantastic explanation. Subbed.
@MythShadow-b5c
@MythShadow-b5c 4 месяца назад
Hello Kyle, nice video and cleared explanation. I got a question regard the container can we make it as draggable too? to am tryin to make my blazor component draggable so i can make my ui more dynamic. Thank you!
@SelKv22
@SelKv22 Год назад
How can I drag elements inside container grid Left/right Top/bottom. Just like mobile icons
@chandansayed8745
@chandansayed8745 4 года назад
Great one. But I have a question about how to save the list on memory. Can you make a video? Please.
@maskman4821
@maskman4821 4 года назад
I know what you mean, the drag-and-drop can be applied on todolist app. there are a few examples on codepen, you can check it out !!!
@chandansayed8745
@chandansayed8745 4 года назад
@@maskman4821 will you please share a link?
@maskman4821
@maskman4821 4 года назад
@@chandansayed8745 the edit feature is not implemented yet because I still am figuring out, stephenlaichaowen.github.io/my-ultimate-todolist/
@nameLastname786
@nameLastname786 9 месяцев назад
Thank you !
@atlicervantes6187
@atlicervantes6187 2 года назад
Quality video!
@danmusiceasy
@danmusiceasy 3 года назад
This seems very useful for creating for example an online calendar or personal organizer with a nice clean look. How can you save the modifications for this? After you drag the elements and reorganize them I mean. Is there a tutorial that shows that as well?
@Slate245Ivanovo
@Slate245Ivanovo 4 года назад
Great tutorial, Kyle. Thank you so much for your work. Can someone clarify this for me: is it ok to have so many events being fired? I understand that the logic we are handling here is pretty simple, but nevertheless wouldn't it cause a performance hit? Bear in mind, I've only worked with frameworks and not vanilla JS, so maybe I'm overreacting to a console being filled with logs :)
@Zhuclam
@Zhuclam 4 года назад
I was thinking the same. It could be a problem in slower machines. You'd have to most liky throttle the events to have a better performance.
@kriskuiper4647
@kriskuiper4647 4 года назад
You can just debounce the events being fired so it's more performant on slower machines.
@kriskuiper4647
@kriskuiper4647 4 года назад
In one word, awesome
@aliadrian2772
@aliadrian2772 Год назад
Can someone explain how did reduce choose which child to return
@ΔημήτριοςΦκιαράς
@ΔημήτριοςΦκιαράς 2 года назад
Thank you! Why does console.log(offset) return two numbers?
@victorgrinan6602
@victorgrinan6602 2 года назад
so nice, how would you do the same in react?
@tanyixuan4639
@tanyixuan4639 3 года назад
woah, thanks a lot. This video is easy to use.
@dgenerationx5220
@dgenerationx5220 Год назад
Can you do video on clone and drop using javascript
@gothamfury
@gothamfury 4 года назад
Thank you for creating this! You're very good at teaching. I'm curious on how we can make the sorted list persist.
@abdielleon3613
@abdielleon3613 3 года назад
Hello Gothamfury. I am not an expert yet, but I will answer your question with a possible answer. One way to "save" the order would involve for each draggable item to be a post saved in a database; then you would save a custom field value with the order number per each item in the list. Having done this, next time you load the page, you would be able to organize your post data in an array sorted by that custom field, and then append them in the DOM in the correct order. This way would be particularly useful if each draggable item is a piece of "content", like an article. → If someone has observations, or a better solution, pls comment. Thanks!
@loulou81400
@loulou81400 3 года назад
+Web Dev Simplified nice tut.. Can you explain the way we can for example open a new tab when the item is drag on his area? To change page for example or to enter in a website.. You drag the item in his area and another page of the website will open
@redpie907
@redpie907 4 года назад
I like your videos very usefull i love them it makes me try it :D and enjoy programming thank you
@sontredis2579
@sontredis2579 4 года назад
People say it's bad to follow tutorials and to just dive in. But if I have no idea how to do something and I want to make a project wouldn't it be good to watch these videos and learn something from them?
@donaldbradbury1100
@donaldbradbury1100 4 года назад
If it helps, I am writing an Electron/node js app for work. I am not a professional developer and am not alway the best person to remember all this stuff. This example is exactly what I need for my app, so I am going to incorporate it in my code and will look like a pro. Many developers do the same. The find a good algorithm to solve a problem and they use it over and over. Welcome to the club.
@BharathBellamkondaC
@BharathBellamkondaC Год назад
can anyone explain the math for how it should be done if its horizontal re ordering items
@alendraone
@alendraone 2 года назад
thanks
@dave6012
@dave6012 2 года назад
I was watching this when my wife got home from work. She asked if I was watching a video with Robert Pattenson 🤣
@dave6012
@dave6012 2 года назад
So I guess what I'm trying to say is, "stay away from my wife."
@alexchen6253
@alexchen6253 3 года назад
thank you
@harshilparmar9076
@harshilparmar9076 4 года назад
Bro great bicep size.I show in thumbnail 💯
@tusharsibal4799
@tusharsibal4799 4 года назад
superbly awesome, that really great. Could you please mention where do you get the stuff like this? Any book or resource?
@akzual50
@akzual50 3 года назад
This is great. Can you do it in blazor with only c# and 1 simple function of jsinterop and no razor pages orxelement definition other than a root component
@frontend-trickss
@frontend-trickss 2 года назад
How to copy able drag and drop in this project ? just hint please.
@yesm4n
@yesm4n Год назад
Perfect.
@reactstack257
@reactstack257 Год назад
Why those events don't support mobile browser , I run the code, it's fine on the desktop browser but android browser it's not work can you help please ? I don't want to use any external library . I try to figure out but no vanilla solution 😔
@belafekete3125
@belafekete3125 3 года назад
This tutorial was awesome! Thank you so much! What is the solution if one of the containers is empty?
@daviddawkins
@daviddawkins 3 года назад
I think it will do the “append” case
@imranali-kn6mv
@imranali-kn6mv 3 года назад
Thanks in advance ..
@nabiisakhanov3522
@nabiisakhanov3522 4 года назад
Hey Kyle, I'd like to ask you one thing. When you declare an object and wanna put a variable as a property with the same name inside of it, you do it like this { offset: offset }, but as far as I know it could be done like just { offset } as long as we don't want to change the name of the property. Is it just for clarity out there's any other reason?
@vincentandrieu5429
@vincentandrieu5429 4 года назад
I'm not Kyle but I can answer: there is no specific reason he used this syntax rather than the other. Both syntaxes are valid and equivalent, he just had to chose one, so he did.
@dipokchandra264
@dipokchandra264 Год назад
It's not a beginner project. But thank you.
@alirezasanati5055
@alirezasanati5055 Год назад
Actually , querySelectorAll is array prototype
@AntonKhavaldzhi
@AntonKhavaldzhi Год назад
Is it work by touching on phones?
@Hoobizone
@Hoobizone 3 года назад
Thanks bro!
@LuisReyes-zs4uk
@LuisReyes-zs4uk 2 года назад
Is there an easy way to also make this work on mobile? Or would the functionality look completely different?
@hamodeyDooba
@hamodeyDooba 3 года назад
this will cause performance issue, isn't'?
@faythe03
@faythe03 3 года назад
Is it the same for mobile?
@tommasini15
@tommasini15 3 года назад
Hello, Can you teach how to do the drag and drop but responsive for mobile! Ty
@tracetv8115
@tracetv8115 Год назад
Very nice video mate! But i have to admin, u drive me crazy with not writing ";" xD
@areasontowritehome
@areasontowritehome 3 года назад
Great tutorial! However, I'm wondering if you're able to help me with this error I'm having. I'm trying to add drag and drop functionality, where users can drag and drop images. I'm currently getting the error "Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'." Looking into it, it seems that the image I'm trying to drop isn't considered a node so it can't be appended. Any idea how to fix this? Is it as simple as turning the image into a node?
@webdevelopers1690
@webdevelopers1690 3 года назад
draggables.reduce( (closest, child, i) => { const box = child.getBoundingClientRect(); const offset = y - box.height / 2 - box.top; if (offset < 0 && offset > closest.offset) { return { offset, element: child }; } else { return closest; } }, { offset: Number.NEGATIVE_INFINITY, } ).element; as we want to add element if offset if greater than NEGATIVE.INFIINTY every number will be greater than NEGETIVE.INFINITY i didn't understand its purpose can you explain?
@sam_sam_sam
@sam_sam_sam 4 года назад
Hey man this video is great and the draggable content works really well in most use cases. I recently implemented this with a list of draggable items that could grow dynamically. I found 2 things: Too many list items, like > 10, caused quite a bit of lag because the getDragAfterElement() method is doing A LOT of calculations for each draggable item, and draggable divs with several child elements experienced some lag while dragging. I fixed the second problem by setting display:none for the child content while dragging, then re-displaying upon dragEnd(). Any ideas how to fix the first problem? Thanks for the great videos man.
@realjayjobes1849
@realjayjobes1849 3 года назад
Yeah I need a solution to this. I thought I did something wrong.
@realjayjobes1849
@realjayjobes1849 3 года назад
setInterval() or setTimeout() - maybe look into debouncing/throttling
@namelysweet8262
@namelysweet8262 4 года назад
So cool !!!!!
@prakharmittal6295
@prakharmittal6295 4 года назад
Can you make one with reactjs too, please?
@gixxerblade
@gixxerblade 3 года назад
Excellent
@maskman4821
@maskman4821 4 года назад
However the drag-and-drop only respondes to mouse events, it is not equaled to touch events on mobile devices, so this feature is not that practical !!!
@andrewkent922
@andrewkent922 4 года назад
Thanks for this video! Very easy to understand and I like that you give explanations about why you're writing certain bits of code. I have a question, really for anyone that can help, regarding programmatically adding in elements using JS and allowing them to be sorted and draggable. Using the code in the tutorial, if I load the elements using python/jinja, then I can drag them. However, if I use JS to add in elements using a button then the draggable is coming back as null. I've read that this is most likely because I'm mixing jquery and vanilla javascript. I have tried searching for vanilla javascript answers though I'm still getting that issue where the container.insertBefore(draggable, afterElement) function is throwing an error because the draggable element is null. I'm pretty new, so if there are any resources I can look at I would appreciate it.
@liveyourdreamsdotbe
@liveyourdreamsdotbe 3 года назад
Do you give the new draggables their event listeners after adding them?
@paulyy32
@paulyy32 2 года назад
@@liveyourdreamsdotbe thank you!!
@ravenjugalbot2170
@ravenjugalbot2170 3 года назад
Can you do something like this using angularjs?
@tone8301
@tone8301 3 года назад
super simple
@daisugabatabata
@daisugabatabata 2 года назад
That's actually easier than using dnd libraries lol
@manuelsaturday8559
@manuelsaturday8559 3 года назад
How to keep clone when you drag it? please help
@sandipbhattacharjee7819
@sandipbhattacharjee7819 3 месяца назад
please explain y- box.top-box.height/2 ... it would mean a lot... kindly explain in detail too..😂 noob programmer as you can see... thank you❤
@superdaveed
@superdaveed 3 года назад
doesn't work on mobiles tho.
@OnlineTutorialsYT
@OnlineTutorialsYT 4 года назад
Nice...I need something like this for my next video.....Thanks bro... your videos are really awesome...Keep it up
@dev10shah
@dev10shah 3 года назад
Wow , Best tutorial teacher
@codingwithkenny6492
@codingwithkenny6492 3 года назад
@Online Tutorials
@jansanchez
@jansanchez 3 года назад
Nice tutorials you're doing
@kenkioqqo
@kenkioqqo 3 года назад
Hey Online Tutorials, were you able to make a video tutorial with what you've learned here? As a beginner, I would love to see how other creators are teaching this concept from their own perspectives...
@The-Dev-Ninja
@The-Dev-Ninja 2 года назад
@@codingwithkenny6492 hi kenny!
@cjwebdev
@cjwebdev 4 года назад
I've learned so much more from your tutorials. I would recommend for someone like me that is learning Javascript. I've been thru so many tutorials in the last few months but it makes more sense when I watch your videos. Thanks!!!
@dimitrispolitis9393
@dimitrispolitis9393 3 года назад
We can also listen for drag events globally with event delegation since the only thing that can move around is the tags. document.addEventListener('dragstart', (e) => { e.target.classList.add('dragging'); }) document.addEventListener('dragend', (e) => { e.target.classList.remove('dragging'); })
@rostyslav5334
@rostyslav5334 4 года назад
That's the thing I was requesting long long time ago, thank You, good job!
@meinpingist1live111
@meinpingist1live111 3 года назад
Is there a way to save it after I've moved it? So if I reload the page it will stay in the same column I moved it to?
@NativeLibyans
@NativeLibyans 3 года назад
I did it by easiest way, my code is complete with IE 6 browser. I used (insertAdjacentElement) and dragenter, dragleave, dragstart, dragend events with if() statement.
@heathen838
@heathen838 2 года назад
That reduce part is waaay to confusing