In this tutorial we will create a Drag and Drop Change Background Color in JavaScript. This tutorial purpose is to teach how to use the drag and drop feature. This will cover all the basic functions that will make this program works. I will provide a sample program to show the actual coding of this tutorial.
This tutorial is simple and easy to understand just follow the instruction I provided and you can do it without a problem. This program can be use to any kind of system that needed to implement a drag and drop function. I will give my best to provide you the easiest way of creating this program Drag and Drop. So let's do the coding.
This is the link for the template that i used for the layout design https://getbootstrap.com/.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/> <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/> </head> <body> <nav class="navbar navbar-default"> <div class="container-fluid"> </div> </nav> <div class="col-md-6 well"> <hr style="border-top:1px dotted #ccc;"/> <div class="col-md-6"> <div class="col-md-12"> <br /> <br /> <br /> <br /> </div> </div> <div class="col-md-6" style="border:1px solid #000; height:200px; padding-top:10%; padding-left:10%;" ondrop="drop(event)" ondragover="dragOver(event)"> </div> </div> </body> </html>
function drop(e){ e.preventDefault(); let data = e.dataTransfer.getData("data"); e.target.style.backgroundColor = data; e.target.innerHTML = ""; } function drag(e){ e.dataTransfer.setData("data", e.target.id); } function dragOver(e){ e.preventDefault(); }
In this code we will create first a method that will detect the appended object called drop()function, this will detect the dropped object and will get the data id. After we getting the object id we will apply the data as the background color of the targeted element. Next we will create a method called drag(), this method will set an object data that will will be carry over while dragging. Lastly we will create a method called called dragOver() function, this will allow the object to be draggable.
The Drag and Drop Change Background Color in JavaScript source code that I provide can be download below. Please kindly click the download button.
There you have it we successfully created Drag and Drop Change Background Color in JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
More Tutorials for JavaScript Language