Jquery draggable jumps on click in Chrome - javascript

I have an issue with jQuery draggable. I have two images in a div with a background image. I can click and drag OK in Firefox but in Chrome they both jump to the top left of the div. If you click and drag again it works OK.
<!doctype html>
<html>
<head>
<title>Untitled Document</title>
<script src="js/jquery-1.11.1.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script src="//code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
<script src="js/jquery.ui.touch-punch.min.js"></script>
<link href="css/styles-test.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="plot_graph"> <img src="http://petentest.co.uk/images/plotgraph-v3.png" width="100%">
<div class="drag_container"> <i style="left:51.32211538461539%;top:40.056022408963585%; color: #00C; cursor: move;" class="pennant-blue fa-5x draggable"> <img src="http://petentest.co.uk/images/pp-blue-pennant-2x.png" width="32" /></i> <i style="left:51.32211538461539%;top:40.056022408963585%; color:#00FFFF; cursor: move;" class="pennant-red fa-5x draggable-manager" > <img src="http://petentest.co.uk/images/pp-red-pennant-2x.png" width="32" /> </i> </div>
</div>
<script>
$( ".draggable" ).draggable({
containment: ".drag_container",
stop: function() {
var plotX = $(this).position().left / $(this).parent().width() * 100;
var plotY = $(this).position().top / $(this).parent().height() * 100;
$('.plot_x').val(plotX);
$('.plot_y').val(plotY);
var java_id = $("input[name=java_id]").val();
//var ajaxurl = 'http://petentest.co.uk/includes/send_user_plot_data.php',
data = {
'performance_plan_id' : java_id,
'user_plot_x': plotX,
'user_plot_y': plotY };
$.post(ajaxurl, data, function (response) {
console.log("Plot saved successfully.");
alert('Your position was saved successfully.');
});
}
});
</script>
<script>
$( ".draggable-manager").draggable({
containment: ".drag_container",
stop: function() {
var plotX = $(this).position().left / $(this).parent().width() * 100;
var plotY = $(this).position().top / $(this).parent().height() * 100;
$('.plot_x').val(plotX);
$('.plot_y').val(plotY);
var java_id = $("input[name=java_id]").val();
var ajaxurl = 'http://petentest.co.uk/includes/send_manager_plot_data.php',
data = {
'performance_plan_id' : java_id,
'manager_plot_x': plotX,
'manager_plot_y': plotY };
$.post(ajaxurl, data, function (response) {
console.log("Plot saved successfully.");
alert('You cannnot move your manager\'s assessment.');
});
}
});
</script>
</body>
</html>
JSFiddle: https://jsfiddle.net/petenaylor/sk75rpuh/

I was able to get it to work by adding "position: absolute" into the styling for your pennant-blue icon.
.pennant-blue {
position: absolute;
}

Related

how to give draggable element into specific location

I am trying to move my JQuery UIdraggable container into div(id="frame") but it is dragging everywhere in the webpage. So how can I move my draggable container into specific div(id="frame").So please give me a way to solve this problem. I am trying to make my own custom product designer plugin for which this my first feature.Here is my code :
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Dragg</title>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.1/themes/base/jquery-ui.css"/>
<style>
#draggable {
overflow:hidden;
width: 100px;
height: 100px;
padding: 0.5em;
background-color: transparent;
}
#frame {
overflow:hidden;
width: 350px;
height: 500px;
padding: 0.5em;
border : 1px solid black;
}
</style>
</head>
<body>
<input type = "file" id="inputFileToLoadOuter">
<input type = "button" onclick = "loadImageFileAsURL(1)" value = "LoadOuterImage">
<input type = "file" id="inputFileToLoadInner">
<input type = "button" onclick = "loadImageFileAsURL(2)" value = "LoadInnerImage">
<div id="frame">
<img src="" id="OuterImg" style="width: 100% ; height:100%" />
</div>
<div id="draggable">
<img src="" id="InnerImg" style="width: 100% ; height:100%" />
</div>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
$( "#draggable" ).resizable().draggable();
} );
function loadImageFileAsURL(pos)
{
if(pos == 1){
var filesSelected = document.getElementById("inputFileToLoadOuter").files;
}else{
var filesSelected = document.getElementById("inputFileToLoadInner").files;
}
if (filesSelected.length > 0)
{
var fileToLoad = filesSelected[0];
if (fileToLoad.type.match("image.*"))
{
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
if(pos == 1){
var imageLoaded = document.getElementById("OuterImg");
}else{
var imageLoaded = document.getElementById("InnerImg");
}
imageLoaded.src = fileLoadedEvent.target.result;
};
fileReader.readAsDataURL(fileToLoad);
}
}
}
</script>
</body>
</html>
plunker : https://plnkr.co/OubL3Uw0G7gi4d01yx0V
Modify your #draggable object to this
$("#draggable").resizable().draggable({
revert: "invalid",
});
and add this to make you #frame droppable
$('#frame').droppable({
accept: '#draggable',
})
Read up the jqueryui docs on this, there is much more you can achieve with this. See here https://jqueryui.com/droppable/#photo-manager
You need to use accept of droppable. Like this
$('#frame').droppable({
accept: '#draggable',
})
It will solve you problem :)
For more knowledge visit
JQuery UI

Rotate and move with JQuery not working

I need to rotate and move an image at the same time, actually works just one time, but then just move and not rotating.
This is what i have:
<!Doctype html>
<html>
<head>
<meta charset ="utf-8">
<title>JQuery Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(MyMain);
function MyMain(){
$(".cartman").hover(MoveCartman,Normal); //on hover Eric Cartman
var v1=100; //variable to move Cartman
function MoveCartman(){
$(this).attr("src","CartmanNude.png");
$(this).css({
"margin-top":v1+"px",
"transform":"rotateZ(-360deg)",
"transition":"1s"
});
if (v1<200){v1+=100;}
else {v1=0;}
}
function Normal(){
$(this).attr("src","CartmanNormal.png");
}
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div style="padding:0px">
<img class="img-responsive cartman" src="CartmanNormal.png">
</div>
</div>
</div>
</body>
</html>
I think this should work fine but I dont know why the function on hover is not working more than just 1 time.
Sorry for my bad english and thanks.
Try substituting lowercase d for D at doctype declaration , adding all to transition value before duration ; css "margin-top": "0px" , "transform": "rotateZ(0deg)" to Normal function
.cartman {
transition: all 1s;
}
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>JQuery Test</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" integrity="sha512-dTfge/zgoMYpP7QbHy4gWMEGsbsdZeCXz7irItjcC3sPUFtf0kuFbDz/ixG7ArTxmDjLXDmezHubeNikyKGVyQ==" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(MyMain);
function MyMain() {
$(".cartman").hover(MoveCartman, Normal); //on hover Eric Cartman
var v1 = 100; //variable to move Cartman
function MoveCartman() {
$(this).attr("src", "http://lorempixel.com/100/100/cats");
$(this).css({
"margin-top": v1 + "px",
"transform": "rotateZ(-360deg)"
});
if (v1 < 200) {
v1 += 100;
} else {
v1 = 0;
}
}
function Normal() {
$(this).attr("src", "http://lorempixel.com/100/100/technics")
.css({
"margin-top": "0px",
"transform": "rotateZ(0deg)"
});
}
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<div style="padding:0px">
<img class="img-responsive cartman" src="http://lorempixel.com/100/100/technics">
</div>
</div>
</div>
</body>
</html>

How to prevent pop-up upon html page load

I have an HTML5 (jsp) page with a link (here) to another page which has a link on it (Home) that, when clicked, pops up a message. However, the message pops up when the page is loaded, which is undesirable. Would someone please look at the below code and give me a solution/suggestion as to how to prevent this behavior? Thank you.
HTML link on first page:
<td class="align-left">Click here</td>
JavaScript:
<script>
function fnCallActionOnSelf(actionName)
{
if(actionName == "newpage.htm"){
nullPageValues(); //here link does not like special characters like apostrophes being sent over by the GET
}
document.forms[0].method = "GET";
document.forms[0].target = '';
document.forms[0].action = actionName;
document.forms[0].submit();
}
function nullPageValues() {
//This is for the here link because it does not like special characters like apostrophes being sent over by the GET
document.getElementById('textField1').value="";
document.getElementById('password').value="";
document.getElementById('Name').value="";
document.getElementById('Address').value="";
document.getElementById('City').value="";
document.getElementById('PhoneNumber').value="";
}
</script>
Jsp page that here link points to:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta content="IE=9; IE=8; IE=7; IE=EDGE; chrome=1" http-equiv="X-UA-Compatible">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<meta content="no-cache, no-store, must-revalidate" http-equiv="Cache-Control">
<meta content="no-cache" http-equiv="Pragma">
<meta content="0" http-equiv="Expires">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<meta charset="utf-8">
</head>
<body>
<div id="container">
<center>
<div style="width: 960px;">
<div>
<div id="Help"
style="vertical-align: middle; display: table-cell;">
<jsp:include page="Help.jsp">
<jsp:param name="isHome" value="no" />
</jsp:include>
</div>
</div>
</div>
</center>
</div>
<div style="clear: both"></div>
<form:form method="post" name="newform"
id="newform" commandName="newformModel" data-parsley-validate="true">
</form:form>
<!-- Lots of stuff here -->
<script src="/project/js/prototype.js" type="text/javascript"></script>
<script src="/project/js/scripts.js" type="JavaScript"></script>
<script src="/project/js/global.js" type="text/javascript"></script>
<script src="/project/js/civem.js" type="text/javascript"></script>
<script src="/project/js/jquery-1.10.2.min.js"></script>
<script src="/project/js/jquery.validate.min.js"></script>
<script src="/project/js/jquery-ui.js"></script>
<script src="/project/js/plugin.js"></script>
<script src="/spiaprojectweb/js/validation.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#dialog" ).dialog();
});
</script>
</body>
</html>
Home link jsp page:
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<meta charset="utf-8">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(document).on("click","a[name='lnkViews']", function (e) {
$(function() {
$( "#dialog" ).dialog();
});
});
function fnCallActionOnSelf(actionName) {
document.forms[0].target = '';
document.forms[0].method = "POST";
document.forms[0].action = actionName; <script>
document.forms[0].submit();
}
function openWindow(anchor)
{
window.open(anchor,'NewWindow','status=0,toolbar=0,resizable=yes,scrollbars=1,width=800,height=600');
}
function findPosition( oElement )
{
oElement=document.getElementById(oElement);
if( typeof( oElement.offsetParent ) != 'undefined' )
{
for( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent )
{
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
}
return posX;
}
else
{
return posX;
}
}
var timeout = 0;
var closetimer = 0;
var ddmenuitem = 0;
// open hidden layer
function mopen(id)
{
// cancel close timer
mcancelclosetime();
// close old layer
if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
ddmenuitem = document.getElementById(id);
var salesAidesPos=findPosition('salesLiId');
salesAidesPos-=20;
ddmenuitem.style.left=salesAidesPos+'px';
ddmenuitem.style.visibility = 'visible';
}
function mopenHelp(id)
{
// cancel close timer
mcancelclosetime();
// close old layer
if(ddmenuitem) ddmenuitem.style.visibility = 'hidden';
ddmenuitem = document.getElementById(id);
var salesAidesPos=findPosition('helpId');
salesAidesPos-=40;
ddmenuitem.style.left=salesAidesPos+'px';
ddmenuitem.style.visibility = 'visible';
}
// close showed layer
function mclose()
{
if(ddmenuitem)
{
ddmenuitem.style.left='0px';
ddmenuitem.style.visibility = 'hidden';
}
}
// go close timer
function mclosetime()
{
closetimer = window.setTimeout(mclose, timeout);
}
// cancel close timer
function mcancelclosetime()
{
if(closetimer)
{
window.clearTimeout(closetimer);
closetimer = null;
}
}
// close layer when click-out
document.onclick = mclose;
</script>
<div id="navcontainer" class="header">
<span class="headtitle"></span> <span class="utility">
<ul class="dropdown">
<span id="helpId">
<li class=""><a name='lnkViews' href="javascript:void(0);" onmouseout="mclosetime()"
onmouseover="javascript: mopenHelp('helpDiv');">Help</a></li>
</span>
</ul>
</span>
</div>
<div id="dialog" title="Help" style="display:none;">
<p><b>Help Message</b></p>
</div>
<div id="spacer">
<img src="/project/img/spacer.gif" />
</div>
<script type="text/javascript">
function setUpdateMessagePosition(oElement) {
oElement = document.getElementById(oElement);
if (typeof (oElement.offsetParent) != 'undefined') {
for ( var posX = 0, posY = 0; oElement; oElement = oElement.offsetParent) {
posX += oElement.offsetLeft;
posY += oElement.offsetTop;
}
if (document.getElementById("updateMsg") != null) {
posX = posX + 8;
posY = posY + 3;
document.getElementById("updateMsg").style.left = posX + "px";
document.getElementById("updateMsg").style.top = posY + "px";
}
}
}
I don't know what much of the above means, or whether it is necessary, but it seems to me that all the action (the code of interest) is in the below snippets from the above jsp file:
<script>
$(document).on("click","a[name='lnkViews']", function (e) {
$(function() {
$( "#dialog" ).dialog();
});
});
</script>
<li class=""><a name='lnkViews' href="javascript:void(0);" onmouseout="mclosetime()"
onmouseover="javascript: mopenHelp('helpDiv');">Help</a></li>
<div id="dialog" title="Help" style="display:none;">
<p><b>Help Message</b></p>
</div>
This is a good time for using sessionStorage! You can do it like this. Change this part of your code:
<script>
$(document).on("click","a[name='lnkViews']", function (e) {
$(function() {
$( "#dialog" ).dialog();
});
});
</script>
to this:
<script>
$(document).on("click","a[name='lnkViews']", function (e) {
$(function() {
if (sessionStorage.visitedalready) {
sessionStorage.visitedalready= 1;
}
else{
$( "#dialog" ).dialog();
}});});
</script>
That session storage variable will be automatically removed once your session was ended.
<script>
$(document).on("click","a[name='lnkViews']", function (e) {
$(function() {
if (sessionStorage.visitedalready) {
sessionStorage.visitedalready= 1;
}
else{
$( "#dialog" ).dialog();
}});});
</script>
I'm not sure how this worked, but I changed the name of my div to an id and renamed the id to helpDialog and changed to use that in the $(document).on function. Then I got rid of the 'e' in the function parameter list for the function in the $(document).on parameter list. That fixed the problem. I'm not sure which of these did the trick.

Angular ng-bind not updated when value changes

I want to bind the content of a span element (that is the current position of the element).
Problem: when I change the element position, angular doesn't update the value of the ng-bind attribute.
This is my html:
!doctype html>
<html lang="en" ng-app="exempleApp">
<head>
<meta charset="utf-8">
<title>jQuery UI Draggable - Default functionality</title>
<link rel="stylesheet" href="jquery-ui.css">
<script src="jquery2.1.4.js"></script>
<script src="jquery-ui.js"></script>
<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="exempleApp.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.movable { width: 150px; height: 150px; padding: 0.5em; background- color: green;}
</style>
<script>
$(function() {
$( ".movable" ).draggable(
{
drag: function(){
var offset = $(this).offset();
var xPos = offset.left;
var yPos = offset.top;
var thisId = $(this).attr('id');
$('#' + thisId + ' .posX').text(xPos);
$('#' + thisId + ' .posY').text(yPos);
}
}
);
});
</script>
</head>
<body ng-controller="imgController as ctrl">
<div id="1" class="ui-widget-content, movable" >
<p>Drag me around</p>
<span class="posX" ng-bind="ctrl.presentation.images[0].posX"></span>
<span class="posY" ng-bind="ctrl.presentation.images[0].posY"></span>
</div>
<div id="2" class="ui-widget-content, movable" >
<p>Drag me around</p>
<span class="posX" ng-bind="ctrl.presentation.images[1].posX"></span>
<span class="posY" ng-bind="ctrl.presentation.images[1].posY"></span>
</div>
<div >
<span ng-bind="ctrl.presentation.images[0].posX"></span>
<span ng-bind="ctrl.presentation.images[0].posY"></span>
</div>
</body>
</html>
And this is my exempleApp.js:
(function() {
var app = angular.module("exempleApp", []);
app.controller('imgController', function(){
this.presentation = pres;
});
var pres = {
images: [
{
posX: "0",
posY: "0"
},
{
posX: "0",
posY: "0"
}
]
};
})();
Thanks for the help
https://docs.angularjs.org/api/ng/directive/ngBind
Typically, you don't use ngBind directly, but instead you use the
double curly markup like {{ expression }} which is similar but less
verbose.
Try this:
<span class="posX">{{ctrl.presentation.images[1].posX}}</span>
Full explanations Databinding in AngularJS
I may have misunderstood your question. It's my understanding that ng- bind binds the value of the html to the value of the object. That is, it's going to read the value from the object, not set it. So when the object changes, the html gets updated. Not the other way around.
#Veo
<p>drag.html</p>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Dragger</title>
<script src="js/jquery.js" type="text/javascript"></script>
<script src="js/jquery-ui.js" type="text/javascript"></script>
<script src="js/angular.js" type="text/javascript"></script>
<script src="js/drag.js" type="text/javascript"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<style>
.movable { width: 150px; height: 150px; padding: 0.5em; background- color: green;}
</style>
<body ng-app="exempleApp">
<div ng-controller="imgController">
<div id="1" class="ui-widget-content movable" drag>
<p>Drag me around</p>
<span class="posX">{{presentation.images[0].posX}}</span>
<span class="posY">{{presentation.images[0].posY}}</span>
</div>
<div id="2" class="ui-widget-content movable" drag>
<p>Drag me around</p>
<span class="posX">{{presentation.images[1].posX}}</span>
<span class="posY">{{presentation.images[1].posY}}</span>
</div>
<div>
<span>#1 .movable = </span>
<span ng-bind="presentation.images[0].posX"></span>
<span ng-bind="presentation.images[0].posY"></span>
</div>
<div>
<span>#2 .movable = </span>
<span ng-bind="presentation.images[1].posX"></span>
<span ng-bind="presentation.images[1].posY"></span>
</div>
</div>
<script>
$(function() {
$( ".movable" ).draggable();
});
</script>
</body>
</html>
<p>drag.js</p>
var app = angular.module("exempleApp", []);
app.controller('imgController', function($scope){
$scope.presentation = pres;
});
app.directive('drag', function(){
return {
link: function(scope, element, attrs){
//initial position
scope.presentation.images[attrs.id-1].posX = element.position().left;
scope.presentation.images[attrs.id-1].posY = element.position().top;
//position after drag
element.on('drag', function(){
scope.presentation.images[attrs.id-1].posX = element.position().left;
scope.presentation.images[attrs.id-1].posY = element.position().top;
console.log(scope.presentation.images[attrs.id-1]);
scope.$apply();
})
}
}
})
var pres = {
images: [
{
posX: "0",
posY: "0"
},
{
posX: "0",
posY: "0"
}
]
};
<p>Note changes: - 1)created a drag directive.then apply it to div.movable.
2)initial position will give you position of draggable div on page load.
3)scope.$apply(); plays important role here without this values will not be apply changes. for more information about $apply visit $apply
<p>if you have any problems just ask me</p>

jQuery, Move Point and Get Coordination

please visit this link and run the code.
http://jsfiddle.net/crisply/mQYVY/
Explain briefly, Green box is added to gray area by clicking [Add box] button.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title></title>
<script src="../Scripts/jquery-1.8.2.js"></script>
<script src="../Scripts/jquery-ui-1.8.24.js"></script>
<style type="text/css">
.draggable {
position: absolute;
width: 10px;
height: 10px;
background: green;
cursor: move;
}
#canvas {
width: 500px;
height: 400px;
background: #ccc;
position: relative;
margin: 2em auto;
}
#results {
text-align: center;
background: yellow;
}
</style>
<script type='text/javascript'>
//<![CDATA[
$(function () {
$(".draggable").draggable({
containment: "parent",
});
$('#btn_add').click(function () {
var htmlData = '<div class="draggable"></div>';
$('#canvas').append(htmlData);
$(".draggable").draggable();
});
});
//]]>
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="canvas">
<div class="draggable"></div>
</div>
<div id="results">coordination</div>
<input type='button' id="btn_add" value='Add box' />
<input type='button' id="btn_getCoord" value="Get Coordination" />
</form>
</body>
</html>
In addition to this code, i want to implement more.
Click the [Add box] button, => point generate random location.
Click the [Get Coordination] button,
=>get the coordination of several points and express result div (yellow area).
Like this.
-Coordination- x:230, y: 222 x:122, y: 233 x:423, y:55
x:50, y:30 ...
Could you please give some components for me?
I really appreciate your help.
http://jsfiddle.net/mQYVY/18/
$(function () {
// This run when the document is ready, so it only effect on first point, it won't effect on new points automatically.
$(".draggable").draggable({
containment: "parent",
});
$('#btn_add').click(function () {
var top = 1 + Math.floor(Math.random() * 390);
var left = 1 + Math.floor(Math.random() * 490);
var htmlData = '<div class="draggable" style="top:'+top+'px;left:'+left+'px;"></div>';
$('.canvas').append(htmlData);
// You need limit draggable containment for new point again.
$(".draggable").draggable({containment: "parent"});
});
$('#btn_getCoord').click(function () {
$('#results').html('-Coordination-');
$('.draggable').each(function(){
var cordInfo = '<br />x: '+$(this).position().left+', y: '+$(this).position().top;
$('#results').append(cordInfo);
});
});
});
Implementation here: http://jsfiddle.net/mQYVY/10/
First part:
var htmlData = $('<div class="draggable"></div>');
var x = Math.floor(Math.random()*501);
var y = Math.floor(Math.random()*401);
htmlData.css({'left': x+'px', 'top': y+'px'});
Second part:
$('#btn_getCoord').click(function() {
var output = '-Coordination-';
$('.draggable').each(function() {
output += '<br />x: ' + $(this).position().left + ', y: ' + $(this).position().top;
});
$('#results').html(output);
});
Updated JS for your first part:
$(function () {
$(".draggable").draggable({
containment: "parent",
});
$('#btn_add').click(function () {
var top = 1 + Math.floor(Math.random() * 390);
var left = 1 + Math.floor(Math.random() * 490);
var htmlData = '<div class="draggable" style="top:'+top+'px;left:'+left+'px;"></div>';
$('.canvas').append(htmlData);
$(".draggable").draggable();
});
});
For the second part follow this link: http://api.jquery.com/offset/

Categories

Resources