How to dragleave fired when hovering a child element in HTML 5?
When a div is made draggable and we hover over a div that executes dragenter and dragleave command, we face a problem when there is a child present inside that div which executes the dragleave command as shown below.
Example 1: Here when hovered over child color disappears.
HTML
<!DOCTYPE html> < html lang = "en" > < head > < meta charset = "UTF-8" /> < meta http-equiv = "X-UA-Compatible" content = "IE=edge" /> < meta name = "viewport" content = "width=device-width, initial-scale=1.0" /> < script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" > </ script > </ head > < style > .yellow { background-color: yellow; } </ style > < body > < div id = "drag" draggable = "true" >Drag me</ div > < hr /> < div id = "drop" > Drop here < p >Child Element</ p > </ div > < script > $("#drop").bind({ dragenter: function () { $(this).addClass("yellow"); }, dragleave: function () { $(this).removeClass("yellow"); }, }); $("#drag").bind({ dragstart: function (e) { e.allowedEffect = "copy"; e.setData("text/plain", "test"); }, }); </ script > </ body > </ html > |
Output: As we can see that when hovered over the child element, the dragleave function executes, and thus the color disappears.
Example 2: To overcome this problem we use a counter which executes the dragleave function only when the counter becomes zero. Here when hovered over child color does not disappear
Javascript
<!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" /> <meta http-equiv= "X-UA-Compatible" content= "IE=edge" /> <meta name= "viewport" content= "width=device-width, initial-scale=1.0" /> <script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js" > </script> </head> <style> .yellow { background-color: yellow; } </style> <body> <div id= "drag" draggable= "true" >Drag me</div> <hr /> <div id= "drop" > Drop here <p>Child Elements</p> </div> <script> var counter = 0; $( "#drop" ).bind({ dragenter: function (ev) { ev.preventDefault(); counter++; $( this ).addClass( "yellow" ); }, dragleave: function () { counter--; if (counter === 0) { $( this ).removeClass( "yellow" ); } }, }); $( "#drag" ).bind({ dragstart: function (e) { e.allowedEffect = "copy" ; e.setData( "text/plain" , "test" ); }, }); </script> </body> </html> |
Output:
Contact Us