How To Build Sortable Drag & Drop With Vanilla Javascript

Поділитися
Вставка
  • Опубліковано 12 вер 2024

КОМЕНТАРІ • 393

  • @vaibhavyadav8726
    @vaibhavyadav8726 3 роки тому +69

    In the end Kyle said, and that's all there is to creating this "SIMPLE"...

  • @mouseclicker4955
    @mouseclicker4955 3 роки тому +44

    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.

    • @user-lc8yw4mk6l
      @user-lc8yw4mk6l 2 роки тому +1

      the formula is eventually the same, but your explanation is more intuitive. Thanks a lot!

    • @RobertFletcherOBE
      @RobertFletcherOBE 2 роки тому +9

      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 Рік тому +1

      @@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 роки тому +34

    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 роки тому +1

      what libaries can you use for drag and drop?

    • @cryptixdaemon7236
      @cryptixdaemon7236 2 дні тому

      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 2 дні тому

      Nice tutorial, but it can't scale easily

  • @cjwebdev
    @cjwebdev 4 роки тому +26

    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!!!

  • @OnlineTutorialsYT
    @OnlineTutorialsYT 4 роки тому +111

    Nice...I need something like this for my next video.....Thanks bro...
    your videos are really awesome...Keep it up

    • @dev10shah
      @dev10shah 3 роки тому +2

      Wow , Best tutorial teacher

    • @codingwithkenny6492
      @codingwithkenny6492 3 роки тому +3

      @Online Tutorials

    • @jansanchez
      @jansanchez 3 роки тому

      Nice tutorials you're doing

    • @kenkioqqo
      @kenkioqqo 3 роки тому +1

      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 роки тому +2

      @@codingwithkenny6492 hi kenny!

  • @dimitrispolitis9393
    @dimitrispolitis9393 3 роки тому +10

    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');
    })

  • @beinyourguard
    @beinyourguard 4 роки тому +97

    you are a very smart programmer, i hope to be like you someday

  • @sjkba
    @sjkba 8 місяців тому +1

    Now that is a high quality, no nonsense video! I thought vanilla JS was just a pain but you presented this incredibly well and made is simple to follow! Love it.

  • @basroos_snafu
    @basroos_snafu 4 роки тому +6

    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!

  • @memoryleakerz
    @memoryleakerz 9 місяців тому +1

    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 14 днів тому

      This! I'm tired of seeing UA-cam videos where the developer spins up react app to do a simple demo. I'm also using as little library as possible.

  • @mark-dev-1
    @mark-dev-1 5 місяців тому

    Damn brother, the way you verbalize as you go, even though you're watching on second screen a finished product, is still amazing.

  • @rostyslav5334
    @rostyslav5334 4 роки тому +7

    That's the thing I was requesting long long time ago, thank You, good job!

  • @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

  • @mikerainey4144
    @mikerainey4144 6 місяців тому

    Brilliant, just what I needed. Your explanation and examples were clear and easy to understand. I didn't just learn what code to copy, learned how and why it works. Thank you.

  • @Yousifalzoubi
    @Yousifalzoubi 3 роки тому +1

    Amazingly simplified explanation! Your channel is now officially my number one go-to for vanilla JavaScript tutorials.

  • @akhmedbejli8657
    @akhmedbejli8657 4 роки тому +3

    I was currently working on my own version of trello and this is a great help.
    Thank you so much.
    Everyone salute for him!

    • @meerule
      @meerule 3 роки тому

      what happened to ur trello project? still working or dropped?

    • @akhmedbejli8657
      @akhmedbejli8657 3 роки тому

      @@meerule I lost motivation. I also gotta do a lot besides this one. So I hope I will make this someday

  • @xKond3i
    @xKond3i 2 роки тому +1

    This man knows, what he's doing.
    Love those explaining videos.
    Thanks! 😎

  • @ahlbf7
    @ahlbf7 3 роки тому

    I`ve put some of my time on C# for the backend, and now I`m strugling with the front-end. Thanks for the video.

  • @keremardcl6759
    @keremardcl6759 Рік тому +1

    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

  • @moominjuice2
    @moominjuice2 2 роки тому

    Beautifully explained and a far more versatile, functional and more succinct code than some of the other tutorials out there. Excellent stuff. Glad I found this channel and really grateful for you sharing on Git.👍

  • @hudstone4732
    @hudstone4732 2 роки тому

    im in internship and you just saved my life. You are a true hero

  • @user-oh5uh4vq4r
    @user-oh5uh4vq4r Рік тому

    Thank you so much! I've been trying to get my drag and drop to work for hours and this video showed me how.

  • @aoisonne1461
    @aoisonne1461 Рік тому

    Been trying to set up drag and drop in my angular app. Using the offset for determining placement was exactly the hint I was looking for, thanks.

  • @donaldbradbury1100
    @donaldbradbury1100 4 роки тому +1

    Thanks for this tutorial. I watched another that also used other events and now I will have to see why the differences. When I incorporate this in my electron/node project, then I will have learned. Thank you so much.

  • @Russ_Paul
    @Russ_Paul Рік тому

    First off great tutorial. I like your use of reduce.
    My brains are getting old and like others, I struggled a bit with the maths.
    Drawing it out, I came up with (box.top + box.height / 2) - y for my offset. If the current y point is above the midpoint it is a positive value, and below a negative value.
    Instead of reduce I used Array.find and a predicate of offset >= 0. This returns the first draggable with a mid point below the current y position.
    Easy coming up with this, when someone else has done all the hard work :)

    • @Russ_Paul
      @Russ_Paul Рік тому

      I used slightly different naming
      return draggables.find((draggable) => {
      const { top, height } = draggable.getBoundingClientRect()
      const middle = top + height / 2
      const offset = middle - currentY
      return offset >= 0
      })

  • @YinPT
    @YinPT 3 роки тому +1

    You explain things in a simple and clear way. Thank you!

  • @RufusVidS
    @RufusVidS 4 роки тому +39

    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 роки тому +5

      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 роки тому +4

      Just don't use 'this' . e.target or e.currentTarget do the same thing

  • @hellelo.5840
    @hellelo.5840 4 роки тому

    My favorite moment in this video is 15:42 .........Man that was very straight no stop...............................Great Content.

  • @jdholwick
    @jdholwick 2 роки тому

    This video really helped me out with a feature I was trying to add to a senior CS university project, so thank you very much!

  • @LucasGoulart
    @LucasGoulart 2 роки тому

    Man, thats 22 minutes just salved my life! Thank you so much!

  • @Snoo29293
    @Snoo29293 3 роки тому +2

    I had to watch it twice but I finally understood it.

  • @edenmaimon6983
    @edenmaimon6983 2 роки тому

    Thank you! It was very complicated for me, but you explained it excellently!
    Starting to follow your channel.

  • @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.

  • @nclsDesign
    @nclsDesign 3 роки тому

    This got randomly recommended to me and I need exactly this later for my current project. Perfect!

  • @orashusedmund7675
    @orashusedmund7675 7 місяців тому

    thank you Kyle, great video, helped me finish a task. 😇

  • @LOLmomentsandfails
    @LOLmomentsandfails 4 роки тому +1

    Your videos helped me become a great developer, without going to school. I wanted to ask if you could do some more web security videos! Thank you!

  • @NativeLibyans
    @NativeLibyans 3 роки тому +1

    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.

  • @panagiotiskoligas9631
    @panagiotiskoligas9631 8 місяців тому

    Kyle you are completely blowing our minds....

  • @milanradinovic6770
    @milanradinovic6770 4 роки тому +2

    Thank you so much for this tutorials. I have learned so much from you. You gave me the inspiration to learn web development.

  • @arshadsiddiqui9071
    @arshadsiddiqui9071 Рік тому +2

    Hey Kyle. I'd love a video going over conditional drag and drop. My use case is that I want to make a board game where you can drag cards wherever but when your card is dragged near a certain spot it should snap into place. I'm currently just researching ways of doing that and got here. (Actually just typing this out gave me an idea lol)

    • @keremardcl6759
      @keremardcl6759 Рік тому +3

      check ClintX and clientY of your cursor. If it is within the coordinates of certain area, make it snap

  • @ondrejexner3688
    @ondrejexner3688 2 роки тому

    This was just awesome. Great work Kyle!

  • @lionelshaghlil1754
    @lionelshaghlil1754 9 місяців тому

    That was professional. Very well and clearly explained, Thank you indeed ,

  • @Yoghaaa
    @Yoghaaa 2 роки тому

    Thank you, Kyle for the video.

  • @SOUVIK_RAY_
    @SOUVIK_RAY_ 4 роки тому +1

    This is an awesome tutorial. You have explained really well. It was very easy to implement it in my code with a slight variation.

  • @BukkyOdunsi
    @BukkyOdunsi Рік тому

    This is the only tutorial of yours that i find hard for me

  • @ДмитрийСенько-с1у
    @ДмитрийСенько-с1у 2 роки тому

    Super helpful. Man, you are awesome, I will watch other videos for sure

  • @pranjalsingh2207
    @pranjalsingh2207 4 роки тому +4

    Awesome tutorial. I wanted to know how to extend this to 2d layout of draggables where we can't just use y coordinate

  • @laviral5311
    @laviral5311 2 роки тому

    Don't know if someone already wrote it but be careful with "drop" event. You will need to prevent default in "dragover" event at least or also in "dragenter". Read some articles about problems of drag api in html 5
    Also thank for a video, very accessible narrative

  • @mr.c7411
    @mr.c7411 3 роки тому

    Best drag and drop video

  • @flyinoctopus
    @flyinoctopus 2 роки тому

    Outstanding tutorial as always, Kyle. I don't know what I'd do without you!

  • @macieq44
    @macieq44 Рік тому

    Such a great video! Thank you!!

  • @theresacampbell9084
    @theresacampbell9084 2 роки тому

    Your job truly is simplifying the web 👌🏾

  • @classicaf
    @classicaf Рік тому

    You are a literal GOAT

  • @syedsmith2151
    @syedsmith2151 2 роки тому

    Magic of drag and drop revealed with simple steps

  • @frankkj1995
    @frankkj1995 3 роки тому

    Amazing tutorial, learnt loads about reduce after confusingly working out ever bit of code. Just a note, if you use the insertbefore function you don't have to check if the element is null, as it will automatically append to the end of the parent container if the element is null. Great video though! Thanks.

    • @usr747
      @usr747 3 роки тому +1

      In this code getDragAfterElement() returns undefined instead of null, so I don't think this code is strictly correct. Because insertBefore() must pass Node or null.
      > Node.insertBefore() - Web APIs | MDN
      > developer.mozilla.org/en-US/docs/Web/API/Node/insertBefore
      > Note: referenceNode is not an optional parameter. You must explicitly pass a Node or null. Failing to provide it or passing invalid values may behave differently in different browser versions.
      This code is comparing afterElement == null instead of afterElement === null, so it just happens to work correctly. If you want to uncheck whether the element is null, the argument to reduce () should be {offset: Number.NEGATIVE_INFINITY, element: null}.

  • @HandcartRule46
    @HandcartRule46 2 роки тому

    Just what I was looking for. Great tutorial

  • @rshum85
    @rshum85 10 місяців тому

    This helped out with my project, thanks so much!

  • @toonice555
    @toonice555 10 місяців тому

    Wow due you figured this out on your own? I wouldn't even know where to start!

  • @MrParktesla
    @MrParktesla 11 днів тому

    Thank you a thousand times :)

  • @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.

  • @ratiabulashvili6491
    @ratiabulashvili6491 3 роки тому

    Brooo, You are the best and Beast at the same time

  • @Fooljuice
    @Fooljuice 3 роки тому

    This was really helpful. Thanks Kyle.

  • @mdzafrullahsarafat1409
    @mdzafrullahsarafat1409 4 роки тому

    Great tutorial. I Always learn new things when I watch your tutorial.

  • @anthonylewis3789
    @anthonylewis3789 3 роки тому

    Love your work, I can honestly say I learn a lot from you

  • @mutaherraza9635
    @mutaherraza9635 2 роки тому

    Awesome explanation. Exactly what I wanted to learn. Thanks a lot!

  • @brian1801
    @brian1801 3 роки тому

    Quite simply -- YOU ROCK! Great content. Even better presentation. Thanks for making such an awesome video.

  • @mangelozzi
    @mangelozzi Рік тому

    Really nice video. Allowed me to implement drag/drop in my situation in 15mins. I optimized it by caching the element being dragged and draggables at dragstart so they are not recalculated every dragover event (which happens a lot). I also get the draggables with querySelectorAll('[draggable="true"]) instead of a new class.

  • @life8261
    @life8261 Рік тому

    Great! This helps me so much with my study. You do a wonderful job! :)

  • @mala235813
    @mala235813 2 роки тому

    Perfect tutorial. Big thanks! Just what I needed.

  • @troyjenkins7189
    @troyjenkins7189 4 роки тому

    Great video, man! Really loved it!

  • @Spirit529
    @Spirit529 3 роки тому

    you saved my life brother, great content!

  • @apollossevere1071
    @apollossevere1071 2 роки тому

    This dude is a beast!!!

  • @JonPeppinck
    @JonPeppinck 2 роки тому +1

    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?

  • @arglebargle17
    @arglebargle17 2 роки тому

    Darn. I did a google search for doing this with web components and your video came up. I got very excited when I saw this was one of your videos. I like the pacing, quality and content. Sadly, I'm bummed out because I'm still trying to figure out the nuances of doing this with custom web components. Some detail continues to elude me.

  • @mykalimba
    @mykalimba 4 роки тому

    Such a cool effect and you make it look easy!

  • @ohad7
    @ohad7 3 роки тому

    Brilliant video man !!
    Thank you for sharing

  • @GabrielCrowe
    @GabrielCrowe 4 роки тому

    This tutorial was wonderful, please keep making these.

  • @md.hasanmahmud1390
    @md.hasanmahmud1390 2 роки тому

    Very Helpful bro
    🙂

  • @lindsayaiello501
    @lindsayaiello501 Рік тому

    This is great, thank you! Have you done something similar but for a TreeView? Like a serious of nested and ? I am working on building now with my base start using your video but thought I would ask if you already did this. Basically I am building a 'favorites' folder structure with drag and drop.

  • @m.sulemankhan3992
    @m.sulemankhan3992 3 роки тому

    Thanks very simple explanation you saved my day

  • @sanghvian
    @sanghvian 4 роки тому

    Amazing tutorial. Like always, learned a lot. Thanks a lot Kyle !

  • @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!!

  • @jonathanmutala8179
    @jonathanmutala8179 Рік тому

    Save my Day bro thx may God bless yu

  • @zylascope
    @zylascope 3 роки тому

    Thanks. That's awesome. A bit complicated for me but I'll get there. A very well explained tutorial.

  • @muhammadfahadameen7669
    @muhammadfahadameen7669 4 роки тому +2

    Thank you for help may Allah protect you and full fil your dreams Ameen

  • @kennethkuah6645
    @kennethkuah6645 3 роки тому +4

    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?

  • @bolbittu
    @bolbittu 4 роки тому

    I implemented a project with similar approach with JavaScript and .NET (in the back end to preserve div’s position). The only difference in my project was that I allowed the div to be placed anywhere on the screen.

  • @markobrien1829
    @markobrien1829 2 роки тому

    Great video. Thank you.

  • @vishalanthony1529
    @vishalanthony1529 3 роки тому

    Helped me alot in my To-do app.

  • @uimonk
    @uimonk 4 роки тому +5

    We would like to know more about you.
    How you do such difficult task effortlessly?

  • @mohammedmahmoud1046
    @mohammedmahmoud1046 2 роки тому

    Awesome tutorial, you are so smart . Thank you

  • @Opyext
    @Opyext 4 роки тому

    wow!!! your explanation is incredible, i have learnt a lot ,thanks

  • @ulviugur3605
    @ulviugur3605 3 роки тому +1

    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 ?

  • @authenticnaturalnoises
    @authenticnaturalnoises 4 роки тому

    Thanks man. You really create awesome content !!!

  • @PankajVerma-zj4vr
    @PankajVerma-zj4vr 3 роки тому

    You just saved my life ! thanks bro

  • @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!

  • @nicholasdittmer4494
    @nicholasdittmer4494 2 роки тому

    Brilliant mate! Thank you very much! Clever stuff. Better than the React libraries I tried and a real feather in the cap for my projects moving forward. Thank You

  • @andrewbaillie2475
    @andrewbaillie2475 3 роки тому +1

    This is brilliant and EXACTLY what I need for a project I am working on. Thank you very much.
    Question (if I may): Is there anyway to have the items COPY into the new field, not actually move?
    Again, Thank you for this tutorial.

    • @cuerojr
      @cuerojr 3 роки тому

      Hi Andrew Did u find the answer for this?

    • @andrewbaillie2475
      @andrewbaillie2475 3 роки тому

      @@cuerojr no I didn't actually.

    • @brendon205
      @brendon205 2 роки тому

      @@andrewbaillie2475 try inserting them twice, on the chosen spot and again in the previous location

  • @aarondz789
    @aarondz789 2 роки тому

    I love your content.Thanks!