I want to react if a user hovers over a border (or into its near).
I got an table for ERD / UML diagrams and I want to give the user the opportunity to resize this table by dragging the tables border. I am working with jQuery and pure JS. My tables are rectangles and its positions are known (x1, x2, y1, y2, width , height , (x1 | y1 ) is top-left, (x2 | y2) is bottom-right ). Every table has the class "diagram" , so I thought about triggering the ."diagram".hover and check the mouse position, but this would be non performant.
I am mainly searching for idears, but short examples would be great.
Code update:
http://codepad.org/3xr8H39m
Wrap it in a wrapper and prevent event happening in its children. See below:
var border = document.getElementById("border");
border.onmouseover = function(e) {
if(e.target !== e.currentTarget) return;
console.log("border-hover")
}
#border {
padding: 4px;
background: blue;
box-sizing: border-box;
cursor: pointer;
}
.box{
height: 100px;
width: 100%;
background: white;
cursor: default;
}
<div id="border">
<div class="box"></div>
</div>
As I know, there is no special method to catch hovering over borders, so you will need some workaround. The first way is to create external container wrapped around the table, with some pixels padding, so you will have some border, and detect hovering over both external container and the inner table, like here:
<script type="text/javascript">
$(function() {
var innerHover = false;
$('.inner_table')
.on('mouseover', function() {
innerHover = true;
})
.on('mouseout', function() {
innerHover = false;
});
// check if we can start resizing
$('.external_wrapper').on('click', function() {
if (!innerHover) {
// we can start resizing!
}
});
});
</script>
<div class="external_wrapper" style="padding: 3px;">
<table class="inner_table">
...
</table>
</div>
The other way is to create thin additional divs along all four table borders and use them as click anchors. This way is user in jQueryUI dialog widget. It is much more flexible as you will not be glued to container borders.
Related
I'm trying to create a roll up div while mouse is over another div. It opens but I'd like it not to close when leaving through the bottom border. Is it possible using JS or JQuery? Here is my current code:
$("#sell1").mouseenter(function(){
$("#rollup1").css("display","inline");
});
$("#rollup1").mouseleave(function(){
$("#rollup1").css("display","none");
});
$("#sell1").mouseleave(function(){
$("#rollup1").css("display","none");
});
When processing the mouseleave, you can get the dimensions of the element and see whether the event's pageY is below the element:
$("#rollup1").mouseenter(function() {
$("#status").text("Over the element...");
});
$("#rollup1").mouseleave(function(e) {
var $this = $(this);
var bottom = $this.offset().top + $this.height();
if (bottom < e.pageY) {
$("#status").text("Left via bottom edge");
} else {
$("#status").text("Left NOT via bottom edge");
}
});
#rollup1 {
width: 50px;
height: 50px;
border: 1px solid black;
}
<div id="status"> </div>
<div id="rollup1"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
For part of the site I'm working on, I have a set of sidebars that can pull out. To have them hide when the users are done with them, I've set up a div with a click event (see below) so that whenever the user clicks somewhere outside of the sidebar, the sidebar closes. The problem that I'm running into, however, is that the click event handler is grabbing the event, running its method, and then the click event seems to stop. I've tried using return true and a few other things I've found around here and the internet, but the click event just seems to die.
$('.clickaway').click(function() {
$('body').removeClass(drawerClasses.join(' '));
return true;
});
EDIT: Here is a fiddle with an example: https://jsfiddle.net/2g7zehtn/1/
The goal is to have the drawer out and still be able to click the button to change the color of the text.
The issue is your .clickaway layer is sitting above everything that's interactive, such as your button. So clicking the button, you're actually clicking the layer.
One thing you could do is apply a higher stacking order for elements you want to interact with, above the .clickaway layer. For example, if we apply position: relative, like this:
.show-drawerHotkey .ColorButton {
position: relative;
}
The element will now be in a higher stacking order (since it comes after the clickaway, and we've applied no z-index to clickaway)
Here's a fiddle that demonstrates: https://jsfiddle.net/2g7zehtn/5/
Using this somewhat famous SO answer as a guide, you can bind to the $(document).mouseup(); event and determine whether certain "toggling" conditions apply:
[EDIT] - Example updated to illustrate clicking a link outside of the containing div.
// Resource: https://stackoverflow.com/questions/1403615/use-jquery-to-hide-a-div-when-the-user-clicks-outside-of-it
var m = $('#menu');
var c = $('#menuContainer');
var i = $('#menuIcon');
i.click(function() {
m.toggle("slow");
});
$(document).mouseup(function(e) {
console.log(e.target); // <-- see what the target is...
if (!c.is(e.target) && c.has(e.target).length === 0) {
m.hide("slow");
}
});
#menuIcon {
height: 15px;
width: 15px;
background-color: steelblue;
cursor: pointer;
}
#menuContainer {
height: 600px;
width: 250px;
}
#menu {
display: none;
height: 600px;
width: 250px;
border: dashed 2px teal;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm a link outside of the container
<div id="menuContainer">
<div id="menuIcon"></div>
<div id="menu"></div>
</div>
I have a scrollable div container fits multiple "pages" (or div's) inside of it's container.
My goal is to, at any given moment, figure out where inside my red container does it reach the top of my scrollable container. So it can be a constant on scroll event, or a button that triggers this task.
So for example. If I have a absolute div element inside one of my red boxes at top:50px. And if I scroll to where that div element reaches the top of my scrollable container. The trigger should say that I am at 50px of my red container.
I'm having a hard time grasping how to accomplish this but I've tried things like:
$("#pageContent").scroll(function(e) {
console.log($(this).scrollTop());
});
But it doesn't take into account the separate pages and I don't believe it it completely accurate depending on the scale. Any guidance or help would be greatly appreciated.
Here is my code and a jsfiddle to better support my question.
Note: If necessary, I use scrollspy in my project so I could target which red container needs to be checked.
HTML
<div id="pageContent" class="slide" style="background-color: rgb(241, 242, 247); height: 465px;">
<div id="formBox" style="height: 9248.627450980393px;">
<div class="trimSpace" style="width: 1408px; height: 9248.627450980393px;">
<div id="formScale" style="width: 816px; -webkit-transform: scale(1.7254901960784315); display: block;">
<form action="#" id="XaoQjmc0L51z_form" autocomplete="off">
<div class="formContainer" style="width:816px;height:1056px" id="xzOwqphM4GGR_1">
<div class="formContent">
<div class="formBackground">
<div style="position:absolute;top:50px;left:100px;width:450px;height:25px;background-color:#fff;color:#000;">When this reaches the top, the "trigger" should say 50px"</div>
</div>
</div>
</div>
<div class="formContainer" style="width:816px;height:1056px" id="xzOwqphM4GGR_2">
<div class="formContent">
<div class="formBackground"><div style="position:absolute;top:50px;left:100px;width:450px;height:25px;background-color:#fff;color:#000;">This should still say 50px</div></div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
CSS
#pageContent {
position:relative;
padding-bottom:20px;
background-color:#fff;
z-index:2;
overflow:auto;
-webkit-overflow-scrolling: touch;
-webkit-transform: translate(0, 0);
-moz-transform: translate(0, 0);
-ms-transform: translate(0, 0);
transform: translate(0, 0);
}
#formBox {
display: block;
position: relative;
height: 100%;
padding: 15px;
}
.trimSpace {
display: block;
position: relative;
margin: 0 auto;
padding: 0;
height: 100%;
overflow: hidden;
}
#formScale::after {
display: block;
content:'';
padding-bottom:5px;
}
#formScale {
position:relative;
width:816px;
margin:0;
-webkit-transform-origin: 0 0;
-moz-transform-origin: 0 0;
transform-origin: 0 0;
-ms-transform-origin: 0 0;
}
.formContainer {
position:relative;
margin : 0 auto 15px auto;
padding:0;
}
.formContent {
position:absolute;
width:100%;
height:100%;
}
.formBackground {
width:100%;
height:100%;
background-color:red;
}
JS
var PAGEWIDTH = 816;
$(window).resize(function (e) {
zoomProject();
resize();
});
function resize() {
$("#pageContent").css('height', window.innerHeight - 45 + 'px');
}
function zoomProject() {
var maxWidth = $("#formBox").width(),
percent = maxWidth / PAGEWIDTH;
$("#formScale").css({
'transform': 'scale(' + percent + ')',
'-moz-transform': 'scale(' + percent + ')',
'-webkit-transform': 'scale(' + percent + ')',
'-ms-transform': 'scale(' + percent + ')'
});
$(".trimSpace").css('width', (PAGEWIDTH * percent) + 'px');
$("#formBox, .trimSpace").css('height', ($("#formScale").height() * percent) + 'px');
}
zoomProject();
resize();
EDIT:
I don't think I am conveying a good job at relaying what I want to accomplish.
At the moment there are two .formContainer's. When I scroll #pageContainer, the .formContainer divs move up through #pageContainer.
So what I want to accomplish is, when a user clicks the "ME" button or #click (as shown in the fiddle below), I'd like to know where in that particular .formContainer, is it touching the top of #pageContainer.
I do use scroll spy in my real world application so I know which .formContainer is closest to the top. So if you just want to target one .formContainer, that is fine.
I used these white div elements as an example. If I am scrolling #pageContainer, and that white div element is at the top of screen as I am scrolling and I click on "ME", the on click trigger should alert to me that .formContainer is touching the top of #pageContainer at 50px from the top. If, the the red container is just touching the top of #pageContainer, it should say it is 0px from the top.
I hope that helps clear up some misconception.
Here is an updated jsfiddle that shows the kind of action that I want to happen.
I am giving this a stab because I find these things interesting. It might just be a starting point since I have a headache today and am not thinking straight. I'd be willing to bet it can be cleaned up and simplified some.
I also might be over-complicating the approach I took, getting the first visible form, and the positioning. I didn't use the getBoundingClientRect function either.
Instead, I approached it trying to account for padding and margin, using a loop through parent objects up to the pageContent to get the offset relative to that element. Because the form is nested a couple levels deep inside the pageContent element you can't use position(). You also can't use offset() since that changes with scroll. The loop approach allowed me to factor the top margin/padding in. I haven't looked at the other solutions proposed fully so there might be a shorter way to accomplish this.
Keeping in mind that the scale will affect the ACTUAL location of the child elements, you have to divide by your scale percentage when getting the actual location. To do that I moved the scalePercentage to a global var so it was usable by the zoom function and the click.
Here's the core of what I did. The actual fiddle has more logging and junk:
var visForm = getVisibleForm();
var formTop = visForm.position().top;
var parents = visForm.parentsUntil('#pageContent');
var truOffset = 0;
parents.each(function() {
truOffset -= $(this).position().top;
});
// actual location of form relative to pageContent visible pane
var formLoc = truOffset - formTop;
var scaledLoc = formLoc / scalePercent;
Updated Fiddle (forgot to account for scale in get func): http://jsfiddle.net/e6vpq9c8/5/
If I understand your question correctly, what you want is to catch when certain descendant elements reach the top of the outer container, and then determine the position of the visible "page" (div with class formContainer) relative to the top.
If so, the first task is to mark the specific elements that could trigger this:
<div class='triggerElement' style="position:absolute;top:50px;left:100px;width:450px;height:25px;background-color:#fff;color:#000;">When this reaches the top, the "trigger" should say 50px"</div>
Then the code:
// arbitrary horizontal offset - customize for where your trigger elements are placed horizontally
var X_OFFSET = 100;
// determine once, at page load, where outer container is on the page
var outerContainerRect;
$(document).ready(function() {
outerContainerRect = $("#pageContent").get(0).getBoundingClientRect();
});
// when outer container is scrolled
$("#pageContent").scroll(function(e) {
// determine which element is at the top
var topElement = $(document.elementFromPoint(outerContainerRect.left+X_OFFSET, outerContainerRect.top));
/*
// if a trigger element
if (topElement.hasClass("triggerElement")) {
// get trigger element's position relative to page
console.log(topElement.position().top);
}
*/
var page = topElement.closest(".formContainer");
if (page.length > 0) {
console.log(-page.get(0).getBoundingClientRect().top);
}
});
EDIT: Changed code to check formContainer elements rather than descendant elements, as per your comment.
http://jsfiddle.net/j6ybgf58/23/
EDIT #2: A simpler approach, given that you know which formContainer to target:
$("#pageContent").scroll(function(e) {
console.log($(this).scrollTop() - $("#xzOwqphM4GGR_1").position().top);
});
http://jsfiddle.net/rL4Ly3yy/5/
However, it still gives different results based on the size of the window. This seems unavoidable - the zoomProject and resize functions are explicitly resizing the content, so you would have to apply the inverse transforms to the number you get from this code if you want it in the original coordinate system.
I do not fully understand what it is that you are needing, but if i am correct this should do the trick
$("#pageContent").scroll(function(e) {
// If more then 50 pixels from the top has been scrolled
// * if you want it to only happen at 50px, just execute this once by removing the scroll listener on pageContent
if((this.scrollHeight - this.scrollTop) < (this.scrollHeight - 50)) {
alert('it is');
}
});
ScrollHeight is the full height of the object including scrollable pixels.
ScrollTop is the amount of pixels scrolled from the top.
You can use waypoints to detect the position of divs based on where you're scrolling.
Here is a link to their official website's example: http://imakewebthings.com/waypoints/shortcuts/inview/
i want to make a draggable image in jquery.
first of all my experience with jquery is 0. having said that let me describe what i want to achieve. i have fixed width/height div. and the image contained inside the div is large in size. so i want the image to be draggable inside that div so that the user can see the entire image.
can someone help. pls be a little elaborate about the procedure considering my jquery fluency.
You can use the following;
$(function() {
$("#draggable").draggable();
});
.container {
margin-top: 50px;
cursor: move;
}
#screen {
overflow: hidden;
width: 200px;
height: 200px;
clear: both;
border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<div class="container">
<div id="screen">
<img src="https://picsum.photos/200/200" class="drag-image" id="draggable" />
</div>
</div>
You want the jQuery Draggable UI tool. The code for this, as with all jQuery, is very simple:
$(document).ready(function(){
$("#draggable").draggable();
});
Will create a draggable object from a standard html tag (the IMG in your case). And for limiting it's mobility to a specific region, you would look into its containment option.
Update: "What is '#draggable' and 'ready'"?
'#draggable' represents the element that you want to be able to drag. The hash (#) symbol represents an ID. When you add your image tags, may give give it an id like the following:
<img src="myimage.jpg" id="draggable" />
That will make the javascript above make your image draggable, because it has the '#draggable' id that the jQuery is looking for.
'.ready()' is the method that is automagically raised by your browser once the page is finished loading. Developers are encouraged by the jQuery group to place all jQuery code within this method to ensure all of the elements on the page are completely loaded prior to any jQuery code attempts to manipulate them.
to limit to a region for this example, containment is not much of a help.
I have implemented this for vertical only scroll, needs enhancement for horizontal limit:
stop: function(event, ui) {
var helper = ui.helper, pos = ui.position;
var h = -(helper.outerHeight() - $(helper).parent().outerHeight());
if (pos.top >= 0) {
helper.animate({ top: 0 });
} else if (pos.top <= h) {
helper.animate({ top: h });
}
}
$('#dragMe').draggable({ containment: 'body' });
This code will make it posible to drag the div with the ID of dragMe where ever you want inside the body of the document. You can also write a class or id as containment.
$('#dragMe').draggable({ containment: '#container' });
This code will make the div dragMe able to be draggable inside of the id container.
Hope this helps otherwise you should be able to find your answer here http://jqueryui.com/demos/draggable/
Expanding on the answer from PH. this will provide an elastic bounceback whenever the image is dragged to the point the underlying container is exposed:
stop: function(event, ui) {
var helper = ui.helper, pos = ui.position;
var h = -(helper.outerHeight() - $(helper).parent().outerHeight());
var w = -(helper.outerWidth() - $(helper).parent().outerWidth());
if (pos.top <= h) {
helper.animate({ top: h });
} else if (pos.top > 0) {
helper.animate({ top: 0 });
}
if (pos.left <= w) {
helper.animate({ left: w });
} else if (pos.left > 0) {
helper.animate({ left: 0 });
}
}
It should be a combination of CSS and JavaScript. The steps to do should be:
Make it on top of all other elements (which property to specify?)
Catch the event when it is clicked (which event to listen to?)
Move the div as mouse moves.
But what are the details?
The jQuery Way:
Check out the jQueryUI addons draggable and droppable.
Literally hundreds of hours have been invested into the jQuery framework to make complicated tasks like this almost trivial. Take advantage of the jQuery team's efforts to make programming rich cross-browser applications easier on us all ;)
Chuck Norris' Way:
If you insist on trying this with raw javascript. You'll want to do a few things. One, programmatically set all draggable items to a relative/absolute positioning. If you click a particular item, cause it's top/left values in CSS to reflect the changes made by the x,y axis of the mouse until the click is released. Additionally, you'll want to update the z-index of each draggable when it's clicked to bring it into view.
Tutorial: How to Drag and Drop with Javascript
make it absolute positioned, with a high z-index.
check for onmousedown of the div.
use the event's mouseX and mouseY attributes to move the div.
Here's an example from Javascript, the Definitive Guide (updated here):
/**
* Drag.js: drag absolutely positioned HTML elements.
*
* This module defines a single drag() function that is designed to be called
* from an onmousedown event handler. Subsequent mousemove event will
* move the specified element. A mouseup event will terminate the drag.
* If the element is dragged off the screen, the window does not scroll.
* This implementation works with both the DOM Level 2 event model and the
* IE event model.
*
* Arguments:
*
* elementToDrag: the element that received the mousedown event or
* some containing element. It must be absolutely positioned. Its
* style.left and style.top values will be changed based on the user's
* drag.
*
* event: ethe Event object for the mousedown event.
*
* Example of how this can be used:
* <script src="Drag.js"></script> <!-- Include the Drag.js script -->
* <!-- Define the element to be dragged -->
* <div style="postion:absolute; left:100px; top:100px; width:250px;
* background-color: white; border: solid black;">
* <!-- Define the "handler" to drag it with. Note the onmousedown attribute. -->
* <div style="background-color: gray; border-bottom: dotted black;
* padding: 3px; font-family: sans-serif; font-weight: bold;"
* onmousedown="drag(this.parentNode, event);">
* Drag Me <!-- The content of the "titlebar" -->
* </div>
* <!-- Content of the draggable element -->
* <p>This is a test. Testing, testing, testing.<p>This is a test.<p>Test.
* </div>
*
* Author: David Flanagan; Javascript: The Definitive Guide (O'Reilly)
* Page: 422
**/
function drag(elementToDrag, event)
{
// The mouse position (in window coordinates)
// at which the drag begins
var startX = event.clientX, startY = event.clientY;
// The original position (in document coordinates) of the
// element that is going to be dragged. Since elementToDrag is
// absolutely positioned, we assume that its offsetParent is the
//document bodt.
var origX = elementToDrag.offsetLeft , origY = elementToDrag.offsetTop;
// Even though the coordinates are computed in different
// coordinate systems, we can still compute the difference between them
// and use it in the moveHandler() function. This works because
// the scrollbar positoin never changes during the drag.
var deltaX = startX - origX, deltaY = startY - origY;
// Register the event handlers that will respond to the mousemove events
// and the mouseup event that follow this mousedown event.
if (document.addEventListener) //DOM Level 2 event model
{
// Register capturing event handlers
document.addEventListener("mousemove", moveHandler, true);
document.addEventListener("mouseup", upHandler, true);
}
else if (document.attachEvent) //IE 5+ Event Model
{
//In the IE event model, we capture events by calling
//setCapture() on the element to capture them.
elementToDrag.setCapture();
elementToDrag.attachEvent("onmousemove", moveHandler);
elementToDrag.attachEvent("onmouseup", upHandler);
// Treat loss of mouse capture as a mouseup event.
elementToDrag.attachEvent("onclosecapture", upHandler);
}
else //IE 4 Event Model
{
// In IE 4, we can't use attachEvent() or setCapture(), so we set
// event handlers directly on the document object and hope that the
// mouse event we need will bubble up.
var oldmovehandler = document.onmousemove; //used by upHandler()
var olduphandler = document.onmouseup;
document.onmousemove = moveHandler;
document.onmouseup = upHandler;
}
// We've handled this event. Don't let anybody else see it.
if (event.stopPropagation) event.stopPropagation(); // DOM Level 2
else event.cancelBubble = true; // IE
// Now prevent any default action.
if (event.preventDefault) event.preventDefault(); // DOM Level 2
else event.returnValue = false; // IE
/**
* This is the handler that captures mousemove events when an element
* is being dragged. It is responsible for moving the element.
**/
function moveHandler(e)
{
if (!e) e = window.event; // IE Event Model
// Move the element to the current mouse position, adjusted as
// necessary by the offset of the initial mouse-click.
elementToDrag.style.left = (e.clientX - deltaX) + "px";
elementToDrag.style.top = (e.clientY - deltaY) + "px";
// And don't let anyone else see this event.
if (e.stopPropagation) e.stopPropagation(); // DOM Level 2
else e.cancelBubble = true; // IE
}
/**
* This is the handler that captures the final mouseup event that
* occurs at the end of a drag.
**/
function upHandler(e)
{
if (!e) e = window.event; //IE Event Model
// Unregister the capturing event handlers.
if (document.removeEventListener) // DOM event model
{
document.removeEventListener("mouseup", upHandler, true);
document.removeEventListener("mousemove", moveHandler, true);
}
else if (document.detachEvent) // IE 5+ Event Model
{
elementToDrag.detachEvent("onlosecapture", upHandler);
elementToDrag.detachEvent("onmouseup", upHandler);
elementToDrag.detachEvent("onmousemove", moveHandler);
elementToDrag.releaseCapture();
}
else //IE 4 Event Model
{
//Restore the original handlers, if any
document.onmouseup = olduphandler;
document.onmousemove = oldmovehandler;
}
// And don't let the event propagate any further.
if (e.stopPropagation) e.stopPropagation(); //DOM Level 2
else e.cancelBubble = true; //IE
}
}
function closeMe(elementToClose)
{
elementToClose.innerHTML = '';
elementToClose.style.display = 'none';
}
function minimizeMe(elementToMin, maxElement)
{
elementToMin.style.display = 'none';
}
HTML5 Drag and Drop
If you are reading this in the year 2017 or later, you might want to have a look at the HTML5 Drag and Drop API:
https://developer.mozilla.org/docs/Web/API/HTML_Drag_and_Drop_API
Example:
<!DOCTYPE HTML>
<html>
<head>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
</script>
<style>
.draggable {
border: 1px solid black;
width: 30px;
height: 20px;
float: left;
margin-right: 5px;
}
#target {
border: 1px solid black;
width: 150px;
height: 100px;
padding: 5px;
}
</style>
</head>
<body>
<h1>Drag and Drop</h1>
<h2>Target</h2>
<div id="target" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<h2>Draggable Elements</h2>
<div id="draggable1" class="draggable" draggable="true" ondragstart="drag(event)"></div>
<div id="draggable2" class="draggable" draggable="true" ondragstart="drag(event)"></div>
<div id="draggable3" class="draggable" draggable="true" ondragstart="drag(event)"></div>
</body>
</html>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
.mydiv {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<h2>Drag and Drop</h2>
<div id="div1" class="mydiv" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>
<div id="div2" class="mydiv" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div3" class="mydiv" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<div id="div4" class="mydiv" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
</body>
</html>
The standard Drag and Drop API is widely recognized to suck big hairy donkey balls. So I wouldn't recommend doing it from scratch. But since that's your question, there are one set of requirements for making something draggable, and one set of requirements for properly setting up a drop zone:
Dragging:
The dom node must have the "draggable" property set to true
Note: e.dataTransfer.setDragImage can be used to set an alternate drag image (the default is a transparent image of the dom node being dragged.
Note2: e.dataTransfer.setData can be used inside the dragstart event to set some data that can be gotten back from the drop event.
Dropping:
In the dragover event, e.preventDefault must be called
In the drop event, e.preventDefault must be called
Example:
<body>
<div id="dragme" draggable="true">Drag Me</div>
<div id="dropzone">Drop Here</div>
</body>
<script>
var dragme = document.getElementById('dragme')
var dropzone = document.getElementById('dropzone')
dragme.addEventListener('dragstart',function(e){
dropzone.innerHTML = "drop here"
})
dropzone.addEventListener('dragover',function(e){
e.preventDefault()
})
dropzone.addEventListener('drop',function(e){
e.preventDefault()
dropzone.innerHTML = "dropped"
})
</script>
However, there are a whole lot of gotchas in using this API, including that:
it takes a lot of work to distinguish between a dragmove event over a dropzone and a dragmove event related to a draggable item
dragmove fires even if your mouse isn't moving
dragleave and dragenter fire even if your mouse isn't moving in or out of the listening dom node (it fires whenever it crosses a child-parent bounary for some stupid reason)
And more..
A better way
I wrote a drag and drop library that makes it a ton easier to use the standard drag and drop API without all those gotchas. Check it out here:
https://github.com/fresheneesz/drip-drop
Yeah, you can use jQuery if you want a bloated library with far more functions than you need! Or if you want to be more of an elitist, use Waltern Zorn's drag and drop library, which is one tenth of the size.
To bring the div on top of other elements you have to assign it a high z-index. Additionally, you can set box-shadow to give a feedback to the user that the element is draggable.
You have to listen for a total of three events: mousedown, mouseup, and mousemove. On mousedown you have to attach a listener on mousemove, which tracks the mouse pointer movements and moves the div accordingly, and on mouseup you have to remove the listener on mousemove.
Moving the div with the mouse is a bit tricky. If you translate the div to the pointer's position, the pointer will always point to the top left corner of the div, even when you click at the bottom right corner. For this, you have to calculate the coordinate difference between the div (top left corner) and the mouse pointer, in the mousedown event handler. Then, you have to subtract that difference from the mouse position before translating the div to that position, in the mousemove event handler.
See the demo for a better idea.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
body,
html {
width: 100%;
height: 100%;
padding: 0px;
margin: 0px;
}
#box {
width: 100px;
height: 100px;
margin: auto;
background-color: lightblue;
}
#box:active {
border: 1px solid black;
box-shadow: 2px 2px 5px 5px #bbb6b6;
}
</style>
</head>
<body>
<div id="box"></div>
</body>
<script>
var box = document.getElementById("box");
var diff = {};
var getBoxPos = function() {
return {
x: box.getBoundingClientRect().x,
y: box.getBoundingClientRect().y
};
};
var calcDiff = function(x, y) {
var boxPos = getBoxPos();
diff = {
x: x - boxPos.x,
y: y - boxPos.y
};
};
var handleMouseMove = function(event) {
var x = event.x;
var y = event.y;
x -= diff.x;
y -= diff.y;
console.log("X " + x + " Y " + y);
box.style.position = "absolute";
box.style.transform = "translate(" + x + "px ," + y + "px)";
};
box.addEventListener("mousedown", function(e) {
calcDiff(e.x, e.y);
box.addEventListener("mousemove", handleMouseMove, true);
});
box.addEventListener("mouseup", function(e) {
console.log("onmouseup");
box.removeEventListener("mousemove", handleMouseMove, true);
});
</script>
</html>
You can do this by using following code
$(function() {
$("#imageListId").sortable({
update: function(event, ui) {
getIdsOfImages();
} //end update
});
});
function getIdsOfImages() {
var values = [];
$('.listitemClass').each(function(index) {
values.push($(this).attr("id")
.replace("imageNo", ""));
});
$('#outputvalues').val(values);
}
/* text align for the body */
body {
text-align: center;
}
/* image dimension */
img {
height: 200px;
width: 350px;
}
/* imagelistId styling */
#imageListId {
margin: 0;
padding: 0;
list-style-type: none;
}
#imageListId div {
margin: 0 4px 4px 4px;
padding: 0.4em;
display: inline-block;
}
/* Output order styling */
#outputvalues {
margin: 0 2px 2px 2px;
padding: 0.4em;
padding-left: 1.5em;
width: 250px;
border: 2px solid dark-green;
background: gray;
}
.listitemClass {
border: 1px solid #006400;
width: 350px;
}
.height {
height: 10px;
}
<link href="https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>
Drag Drop feature
</title>
</head>
<body>
<h1 style="color:green">GeeksforGeeks</h1>
<b>Drag and drop using jQuery UI Sortable</b>
<div class="height"></div><br>
<div id = "imageListId">
<div id="imageNo1" class = "listitemClass">
<img src="images/geeksimage1.png" alt="">
</div>
<div id="imageNo2" class = "listitemClass">
<img src="images/geeksimage2.png" alt="">
</div>
<div id="imageNo3" class = "listitemClass">
<img src="images/geeksimage3.png" alt="">
</div>
<div id="imageNo4" class = "listitemClass">
<img src="images/geeksimage4.png" alt="">
</div>
<div id="imageNo5" class = "listitemClass">
<img src="images/geeksimage5.png" alt="">
</div>
<div id="imageNo6" class = "listitemClass">
<img src="images/geeksimage6.png" alt="">
</div>
</div>
<div id="outputDiv">
<b>Output of ID's of images : </b>
<input id="outputvalues" type="text" value="" />
</div>
</body>
</html>