Home > Web Front-end > HTML Tutorial > Execute a script when an element is dragged in HTML?

Execute a script when an element is dragged in HTML?

王林
Release: 2023-09-16 22:05:06
forward
733 people have browsed it

Execute a script when an element is dragged in HTML?

Use the ondragover attribute in HTML HTML to execute a script when an element is dragged in HTML.

Example

You can try running the following code to achieve ondragover Properties -

<!DOCTYPE HTML>
<html>
   <head>
      <style>
         .drag {
            float  : left;
            width  : 100px;
            height : 35px;
            border : 2px dashed #876587;
            margin : 15px;
            padding: 10px;
         }
      </style>
   </head>
   <body>
      <div class = "drag" ondrop = "drop(event)" ondragover = "dropNow(event)">
         <p ondragstart = "dragStart(event)" ondrag = "draggingNow(event)" draggable = "true" id="dragtarget">Drag!</p>
      </div>
      <div class = "drag" ondrop = "drop(event)" ondragover = "dropNow(event)"></div>
      <div id = "box"></div>
      <p>Drag the left box to the right or drag the right box to the left.</p>
      <script>
         function dragStart(event) {
            event.dataTransfer.setData("Text", event.target.id);
          }
         function draggingNow(event) {
            document.getElementById("box").innerHTML = "Dragged successfully!";
         }
         function dropNow(event) {
            event.preventDefault();
         }
         function drop(event) {
            event.preventDefault();
            var data = event.dataTransfer.getData("Text");
            event.target.appendChild(document.getElementById(data));
            document.getElementById("box").innerHTML = "The element dropped successfully!";
         }
      </script>
   </body>
</html>
Copy after login

The above is the detailed content of Execute a script when an element is dragged in HTML?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template