I have a real problem over here. I want a function to get called only when an object is clicked and when when the mouse is moved over the object. Here is a (syntax-retarded) example to get your understanding:
<div onMouseMove+onMouseDown="function()" ... ></div>
I was thinking of a way to solve this. What if I make a onMouseDown that trigger a function that will change the name of my onMouseMove - function, and use a "filler" or a "substitute" function? Let me explain:
<div id="object" onMouseMove="substituteFiller()" onMouseDown="nameChanger()" ... ></div>
<script>
function nameChanger(){
document.getElementById("object").onMouseMove = "theRealFunction()";
}
</script>
<script>
function theRealFunction() ...
When I move the mouse over the object nothing will happen, because the function substituteFiller() won't work. But, when the mouse has clicked on the object the onMouseMove- function will be the correct one, theRealFunction(), and theRealFunction() will now get called when the mouse moves.
This way I could activate/call theRealFunction() only when the object is clicked and when the mouse moved. However, it does not work.
To be clear: how can I change the name of the function that is being called? How can I make a function to be called only when an object is clicked and mouse moved?
Best regards, hope you understood! If not, comment I guess!
Okay, all you need to do is separately register 3 event handlers:
mouse down
mouse up
mouse move
You will have a boolean flag toggled to true and false on mouse down and up respectively. Then, on the mouse move handler, you need to check if the flag is true, which would mean the mouse button is down. Finally, we check to see if the cursor has actually moved from its initial position.
Here's the JSFiddle.
var example = document.getElementById("example");
var position = {
X: 0,
Y: 0
};
example.onmousedown = function (down) {
downFlag = true;
// Record click position
position.X = down.clientX;
position.Y = down.clientY;
};
example.onmouseup = function (up) {
downFlag = false;
};
example.onmousemove = function (move) {
if (downFlag) {
if (position.X !== move.clientX || position.Y !== move.clientY) {
// Do stuff here
}
}
};
Its a part from one of my web page..Check It out.May this will help you..
<div id="Log_frm">
<fieldset id="fld_1">
<!--<legend>Log In</legend>-->
<div id="log_l" onmouseover="dv_in();" onmouseout="dv_out();" style="background-color:#0C93D4;font-size: 15px;height: 30px;padding: 7px 32px 0px 32px;font-weight:bold; float: left;-webkit-border-top-left-radius: 5px;">
Log In
</div>
<div id="log_r" onmouseover="dv_out();" onmouseout="dv_in();"style="background-color: #0C93D4;font-size: 15px;font-weight:bold; float: right;height: 30px;padding: 7px 14px 0px 12px;-webkit-border-top-right-radius: 5px;">
Need Any Help
</div >
</fieldset>
</div>
<style>
#Log_frm {
width: 250px;
height: 60px;
margin-top: 10px;
position: absolute;
font-size: 12px;
float: right;
right: 0px;
}
#Log_frm a {
color: #fff;
text-decoration: underline !important;
left: auto;
margin-right: auto;
}
<script type="text/javascript">
function dv_in() {
log_l.style.backgroundColor="#06C";
log_r.style.backgroundColor="#0C93D4";
}
function dv_out() {
log_l.style.backgroundColor="#0C93D4";
log_r.style.backgroundColor="#06C";
}
</script>
Regds..
Related
I have always used the mouseover event, but while reading the jQuery documentation I found mouseenter. They seem to function exactly the same.
Is there a difference between the two, and if so when should I use them?
(Also applies for mouseout vs mouseleave).
You can try out the following example from the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.
var i = 0;
$("div.overout")
.mouseover(function() {
i += 1;
$(this).find("span").text("mouse over x " + i);
})
.mouseout(function() {
$(this).find("span").text("mouse out ");
});
var n = 0;
$("div.enterleave")
.mouseenter(function() {
n += 1;
$(this).find("span").text("mouse enter x " + n);
})
.mouseleave(function() {
$(this).find("span").text("mouse leave");
});
div.out {
width: 40%;
height: 120px;
margin: 0 15px;
background-color: #d6edfc;
float: left;
}
div.in {
width: 60%;
height: 60%;
background-color: #fc0;
margin: 10px auto;
}
p {
line-height: 1em;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="out overout">
<span>move your mouse</span>
<div class="in">
</div>
</div>
<div class="out enterleave">
<span>move your mouse</span>
<div class="in">
</div>
</div>
In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from outside this element to this element.
Or as the mouseover() docs put it:
[.mouseover()] can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.
Mouseenter and mouseleave do not react to event bubbling, while mouseover and mouseout do.
Here's an article that describes the behavior.
As is often true with questions like these, Quirksmode has the best answer.
I would imagine that, because one of jQuery's goals is to make things browser agnostic, that using either event name will trigger the same behavior. Edit: thanks to other posts, I now see this is not the case
$(document).ready(function() {
$("#outer_mouseover").bind
("Mouse Over Mouse Out",function(event){
console.log(event.type," :: ",this.id);})
$("#outer_mouseenter").bind
("Mouse enter Mouse leave",function(event){
console.log(event.type," :: ",this.id);})
});
I have a page with two areas. There are boxes in each area. If the user clicks on a box in the top area, it gets moved to the bottom and vice versa. This works fine for the first movement. Theoretically, I should be able to move them back and forth between sections as I please.
Box HTML:
<div id="top-area">
<div class="top-box" id="blue-box"></div>
<div class="top-box" id="yellow-box"></div>
<div class="top-box" id="green-box"></div>
</div>
<hr/>
<div id="bottom-area">
<div class="bottom-box" id="red-box"></div>
<div class="bottom-box" id="gray-box"></div>
</div>
I use jQuery.remove() to take it out of the top section and jQuery.append() to add it to the other. However, when I try to move a box back to its original position, the event that I have created to move them doesn't even fire.
jQuery/JavaScript:
$(".top-box").on('click', function ()
{
var item = $(this);
item.remove();
$(this).removeClass("top-box").addClass("bottom-box");
$("#bottom-area").append(item);
});
$(".bottom-box").on('click', function ()
{
var item = $(this);
item.remove();
$(this).removeClass("bottom-box").addClass("top-box");
$("#top-area").append(item);
});
I have verified that the classes I am using as jQuery selectors are getting added/removed properly. I am even using $(document).on() to handle my event. How come my boxes are not triggering the jQuery events after they are moved once?
Please see the Fiddle: http://jsfiddle.net/r6tw9sgL/
Your code attaches the events on the page load to the elements that match the selector right then.
If you attach the listener to #top-area and #bottom-area and then use delegated events to restrict the click events to the boxes, it should work like you expect. See .on: Direct and Delegated Events for more information.
Use the below JavaScript:
$("#top-area").on('click', '.top-box', function ()
{
var item = $(this);
item.remove();
$(this).removeClass("top-box").addClass("bottom-box");
$("#bottom-area").append(item);
});
$("#bottom-area").on('click', '.bottom-box', function ()
{
var item = $(this);
item.remove();
$(this).removeClass("bottom-box").addClass("top-box");
$("#top-area").append(item);
});
Alternatively:
You could also change .on() to .live(), which works for "all elements which match the current selector, now and in the future." (JSFiddle)
JSFiddle
Here's another way you could work it:
function toBottom ()
{
var item = $(this);
item.remove();
item.off('click', toBottom);
item.on('click', toTop);
$(this).removeClass("top-box").addClass("bottom-box");
$("#bottom-area").append(item);
}
function toTop ()
{
var item = $(this);
item.remove();
item.off('click', toTop);
item.on('click', toBottom);
$(this).removeClass("bottom-box").addClass("top-box");
$("#top-area").append(item);
}
$(".top-box").on('click', toBottom);
$(".bottom-box").on('click', toTop);
#top-area, #bottom-area {
height: 100px;
border: 1px solid black;
padding: 10px;
}
.top-box::before {
content: "Top";
}
.bottom-box::before {
content: "Bottom";
}
#blue-box, #red-box, #yellow-box, #green-box, #gray-box {
width: 100px;
cursor: pointer;
float: left;
margin: 0 5px;
text-align: center;
padding: 35px 0;
}
#blue-box {
background-color: blue;
}
#red-box {
background-color: red;
}
#yellow-box {
background-color: yellow;
}
#green-box {
background-color: green;
}
#gray-box {
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-area">
<div class="top-box" id="blue-box"></div>
<div class="top-box" id="yellow-box"></div>
<div class="top-box" id="green-box"></div>
</div>
<hr/>
<div id="bottom-area">
<div class="bottom-box" id="red-box"></div>
<div class="bottom-box" id="gray-box"></div>
</div>
This basically removes the listener that switched the object to bottom to a listener that switches the object to the top and viceversa.
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 always used the mouseover event, but while reading the jQuery documentation I found mouseenter. They seem to function exactly the same.
Is there a difference between the two, and if so when should I use them?
(Also applies for mouseout vs mouseleave).
You can try out the following example from the jQuery doc page. It's a nice little, interactive demo that makes it very clear and you can actually see for yourself.
var i = 0;
$("div.overout")
.mouseover(function() {
i += 1;
$(this).find("span").text("mouse over x " + i);
})
.mouseout(function() {
$(this).find("span").text("mouse out ");
});
var n = 0;
$("div.enterleave")
.mouseenter(function() {
n += 1;
$(this).find("span").text("mouse enter x " + n);
})
.mouseleave(function() {
$(this).find("span").text("mouse leave");
});
div.out {
width: 40%;
height: 120px;
margin: 0 15px;
background-color: #d6edfc;
float: left;
}
div.in {
width: 60%;
height: 60%;
background-color: #fc0;
margin: 10px auto;
}
p {
line-height: 1em;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="out overout">
<span>move your mouse</span>
<div class="in">
</div>
</div>
<div class="out enterleave">
<span>move your mouse</span>
<div class="in">
</div>
</div>
In short, you'll notice that a mouse over event occurs on an element when you are over it - coming from either its child OR parent element, but a mouse enter event only occurs when the mouse moves from outside this element to this element.
Or as the mouseover() docs put it:
[.mouseover()] can cause many headaches due to event bubbling. For instance, when the mouse pointer moves over the Inner element in this example, a mouseover event will be sent to that, then trickle up to Outer. This can trigger our bound mouseover handler at inopportune times. See the discussion for .mouseenter() for a useful alternative.
Mouseenter and mouseleave do not react to event bubbling, while mouseover and mouseout do.
Here's an article that describes the behavior.
As is often true with questions like these, Quirksmode has the best answer.
I would imagine that, because one of jQuery's goals is to make things browser agnostic, that using either event name will trigger the same behavior. Edit: thanks to other posts, I now see this is not the case
$(document).ready(function() {
$("#outer_mouseover").bind
("Mouse Over Mouse Out",function(event){
console.log(event.type," :: ",this.id);})
$("#outer_mouseenter").bind
("Mouse enter Mouse leave",function(event){
console.log(event.type," :: ",this.id);})
});
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>