jQuery, Move Point and Get Coordination - javascript

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/

Related

how to drop an element into a div and retrieve the coordinates relative to the div element?

i have a div element with id="drag", if a div element with id='drag' is dragged and dropped onto a div element with id="drop", it will display the coordinates value relative to the div element with id="drop" . I've managed to retrieve the coordinates relative to the div id="drop", but when the page is scrolled, the Y value also changes. how to solve this so that when the page is scrolled the Y value remains relative to the div with id='drop'? here is my code below
`
`<!DOCTYPE html>
<html lang="en">
<head>
<title>jQuery UI Droppable</title>
</head>
<body style="height: 200vh">
<div
id="drop"
style="
width: 600px;
height: 600px;
background-color: brown;
margin: 0 auto;
"
></div>
<div
id="drag"
style="background-color: blue; width: 100px; height: 100px"
></div>
</body>
<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 () {
$("#drag").draggable();
$("#drop").droppable({
accept: "#drag",
drop: function (e) {
var rect = e.target.getBoundingClientRect();
const coordinates = [
Math.round(e.pageX - rect.left),
Math.round(e.pageY - rect.top),
];
console.log(coordinates[0]);
console.log(coordinates[1]);
},
});
});
</script>
</html>`
`
At least from here, it never changes.
you can check it like that:
$(function () {
var coordinates;
$("#drag").draggable();
$("#drop").droppable({
accept: "#drag",
drop: function (e) {
var rect = e.target.getBoundingClientRect();
coordinates = [
Math.round(e.pageX - rect.left),
Math.round(e.pageY - rect.top),
];
setInterval(() => {
console.log(coordinates[0]);
console.log(coordinates[1]);
}, 500);
},
});
});

Pie chart legend not showing - Uncaught TypeError: Cannot set property 'innerHTML' of null

I have to show legends for a pie chart. I have been following below link.
http://jsfiddle.net/vrwjfg9z/
But it does not work for me in below code.
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>ChartJS - Pie Chart</title>
<link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet">
<script src = "https://code.jquery.com/jquery-1.10.2.js"></script>
<script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="jquery-2.1.4.min.js"></script>
<script src="Chart.js"></script>
<script src="veeva-library.js" type="text/javascript"></script>
<link rel="stylesheet" href="styles.css">
<script src="veevaMessages.js" type="text/javascript"></script>
<script src="jquery-ui-1.11.4/external/jquery/jquery.js"></script>
<script src="jquery-ui-1.11.4/jquery-ui.min.js"></script>
<script src="MyInsightsLibrary.js"></script>
</head>
<body onload="init()">
<span style="float: left;margin-left:2em"> <b>Date Range: </b>
<input type="text" id="datepicker" > <b>to </b>
<input type="text" id="datepicker2"> </span><div id = "Alert" style="float:left;margin-left:2em"> Please select a valid Date Range!</div>
<div style="width: 100%; height: 100%;">
<canvas id="mycanvas" style="width: 100%; height: auto;"></canvas> <!--width="300" height="300">-->
</div>
<div id="js-legend" style="display: inline-block;width: 12px; height: 12px; margin-right: 5px;"></div> <!-- class="chart-legend" -->
</body>
<script>
var startDate;
var endDate;
var start;
var end;
$(function() {
$("#datepicker").datepicker({
onSelect: function() {
startDate = $(this).datepicker('getDate');
start = formatDate(startDate);
if( start!=null && end!=null && end>=start)
{document.getElementById('Alert').style.visibility = 'hidden';
init();
}
else {
document.getElementById('Alert').style.visibility = 'visible'; //Will show
}
}
});
$("#datepicker2").datepicker({
onSelect: function() {
endDate = $(this).datepicker('getDate');
end = formatDate(endDate);
alert('skn here s' + startDate);
alert('skn here e' + endDate);
if( start!=null && end!=null && end>=start)
{document.getElementById('Alert').style.visibility = 'hidden';
init();
}
else {
document.getElementById('Alert').style.visibility = 'visible'; //Will show
}
}
});
});
function init(){
var dynamicColors = function() {
var r = Math.floor(Math.random() * 255);
var g = Math.floor(Math.random() * 255);
var b = Math.floor(Math.random() * 255);
return "rgb(" + r + "," + g + "," + b + ")";
}
var data = [
{
value: 270,
color: dynamicColors(), //"cornflowerblue",
highlight: dynamicColors(), //"lightskyblue",
label: "Corn Flower Blue"
},
{
value: 50,
color: dynamicColors(), //"lightgreen",
highlight: dynamicColors(), //"yellowgreen",
label: "Lightgreen"
},
{
value: 40,
color: dynamicColors(), //"orange",
highlight: dynamicColors(),//"darkorange",
label: "Orange"
}
];
var options = {
segmentShowStroke: false,
animateRotate: true,
animateScale: false,
percentageInnerCutout: 50,
tooltipTemplate: "<%= value %>n"
};
var ctx = document.getElementById("mycanvas").getContext("2d");
//draw
var mycanvas = new Chart(ctx).Pie(data,options);
document.getElementById('js-legend').innerHTML = mycanvas.generateLegend();
}
</script>
</html>
I am getting below error in console. I do understand from google search that it needs somewhere to put document.ready or some onload function which I am not sure of.
Error
Uncaught TypeError: Cannot set property 'innerHTML' of null
at init & at onload
Can someone please let me know where I go wrong?
Please find the screenshot how the legend shows for me without rectangular color boxes.
enter image description here
jQuery is not finding your div #js_legend because you did not write it properly in your HTML. It should be this:
<div id="js-legend" style="display: inline-block;width: 12px; height: 12px; margin-right: 5px;"></div>
Instead of this:
</div id="js-legend" style="display: inline-block;width: 12px; height: 12px; margin-right: 5px;"></div>
Something else I noticed is, why are you using the traditional JavaScript document.getElementsById() when you're using jQuery? You ought to use the $ operator, like you're supposed to. I noticed this line that you have.
document.getElementById('js-legend').innerHTML = mycanvas.generateLegend();
This is bad practice in jQuery, and it screws up the flow of your script, it might even make things malfunction.
$("#js-legend").html(mycanvas.generateLegend());
To change the visibility property of your elements, you will want to use the jQuery .css() function. Also, have a look at this question. You should use the following syntax, as opposed to invoking .style.visibility the way you would in traditional JavaScript.
$("#Alert").css("visibility", "hidden");

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

Jquery draggable jumps on click in Chrome

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;
}

Smooth scroll UI draggable

I'm having a problem with jQuery UI draggable..
I with to scroll an element within a smaller parent element, so that it creates a kind of viewport.
However, I'm having an issue with the element being dragged as it's snapping to the edges of the port.
Been battling with this for a while now so could really use some help... please :)
Here is an example of the behaviour I'm trying to get : LINK
Here is a jsFiddle : LINK
and sample code:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.9.2/themes/base/jquery-ui.css" />
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<!-- CSS -->
<style type="text/css">
#port{
width:50px;
height:100px;
border:1px solid red;
overflow:hidden;
}
#obj {
width: 100px;
height: 100px;
border: 1px solid black;
cursor: pointer;
border-radius: 10px;
text-align: center;
background-color: lightpink;
}
</style>
<!-- Javascript -->
<script>
$(function ()
{
$("#obj").draggable(
{
containment: "#port",
scroll: false,
axis: 'x'
});
});
</script>
<!-- HTML -->
<div id="port">
<div id="obj">
<p>Drag me</p>
</div>
</div>
DEMO
Hope this is what you need, since you specified axis:x , it will move only in x axis
$(function () {
$("#obj").draggable({
scroll: false,
axis: 'x',
});
});
Here is the solution.
<div id="port">
<div id="obj">
<p>This is my new paragraph</p>
</div>
</div>
$(function() {
$( "#obj" ).draggable();
});
Link: http://jsfiddle.net/3HVT5/
It works when you remove the containment: "#port" line in your original code.
DEMO
I guess this is what you need
$(function () {
$("#obj").draggable({
containment: 'parent',
axis: 'x',
drag: function (event, ui) {
var p = ui.helper.position();
$(this).stop().animate({
right: p.right,
left: p.left
}, 400, 'linear');
}
});
});
Found 'a' solution here, but not sure of it's elegance...
<div id="outer"> <!-- position: relative -->
<div id="inner"> <!-- position: absolute -->
<img id="img_1" src="http://media02.hongkiat.com/nature-photography/red-planet.jpg" width="300" height="100" />
</div>
</div>
$(function()
{
var img = $("#img_1").draggable(
{
containment: '#inner',
axis: 'x'
}),
h = img.height(),
w = img.width(),
outer = $('#outer'),
oH = outer.height(),
oW = outer.width(),
iH = h + (h - oH),
iW = w + (w - oW),
iT = '-' + ((iH - oH)/2) + 'px',
iL = '-' + ((iW - oW)/2) + 'px';
$('#inner').css({ width: iW, height: iH, top: iT, left: iL });
})
However, tried it out and it does exactly what I'm after. So failing anything better I will go with this. Here is a fiddle link for you guys to try it out.
Thanks for your help...

Categories

Resources