javascript drag and drop, dragging elements around the page is inaccurite - javascript

so I have a canvas that takes up 100% of the page size and ontop of this canvas are other html elements. I want to make it so any element that has the class game-gui can be dragged round the screen (so users can position them where they want).
the js fiddle for this looks like this:
http://jsfiddle.net/VYJCj/2/
the code for this can be seen below:
$('.game-gui').each(function(i, obj) {
$(obj).on('dragstart', function(event){
var left = parseInt($(obj).css("left"), 10);
var top = parseInt($(obj).css("top"), 10);
event.originalEvent.dataTransfer.effectAllowed = 'move';
var str = (left - event.originalEvent.clientX) + ',' + (top - event.originalEvent.clientY)+ ',' + event.target.id;
event.originalEvent.dataTransfer.setData("text/plain", str);
});
});
this.canvas = $('#game_canvas');
this.canvas.bind('drop', function(event){
event.stopPropagation();
event.preventDefault();
var offset = event.originalEvent.dataTransfer.getData("text/plain").split(',');
console.log(offset);
var obj = $('#' + offset[2]);
var clientX = event.originalEvent.clientX || 0;
var clientY = event.originalEvent.clientY || 0 ;
obj.css('left', ( clientX+ parseInt(offset[0],10)) + 'px');
obj.css('top', ( clientY + parseInt(offset[1],10)) + 'px');
return false;
});
this.canvas.bind('dragover', function(event){
event.preventDefault();
event.originalEvent.dataTransfer.dropEffect = 'move';
return false;
});
as you will be able to see from the demo you can move the elements around the page however they move into different positions then they should! would anyone be able to help me on the matter?

Related

issue with jquery-ui and helper/ghost blocking elements identity

the code below is a standard resizable() jQuery-ui Widget.
how is it possible to know what is the object it being dragged on to ?
i have tried to catch it using the clientX and more... but it did not "deliver" the actual element. i have tried without ghost which was inter-fearing in middle of the way to discover what is layed under. though this is not the issue i guess.
$([selector]).resizable({
//some featurs/options and then
resize:
function (event, obj) {
var x = event.clientX, y = event.clientY,
var elementMouseIsOver = document.elementFromPoint(x, y);
}
});
any help would be appreciated .
take a look on the z-index i have applied to resizable div
i have lowered it conditionally.
so if it is over some other ide'd object, i will then be able to access its properties rather the blocking resizable .
$('document').ready(function () {
$('#resz').resizable({
handles: 'n, s',
resize:
function (event, obj) {
var H = obj.size.height;
var curobj = $(this);
var target = curobj;
var x = event.clientX, y = event.clientY;
var elementMouseIsOver = document.elementFromPoint(x, y);
if (elementMouseIsOver.id != "") //&& elementMouseIsOver.id != this.id)
{
curobj.css("z-index", "-1");
target = $("#" + elementMouseIsOver.id); //.css('display', 'none');
$("#deb").html("found " + target.attr("id") + " at " + target.css("z-index"));
}
}
});
});

Watching for multiple elements without multiple if statements

I have a snippet that on scroll it checks wether an element is in the current viewport.
I now want to add multiple elements into the mix, but I wanted to avoid doing multiple if statements checking for each, I know the following code doesn't work but it is an example of how I would like to do it, is there a way of doing it this way?
var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
// if the element we're actually looking for exists
if (listOfPanels.length){
// check if the element is in the current view using the attached function
// and the event hasn't already fired
if (isElementInViewport(listOfPanels)) {
// do something
}
}
});
try this:
function isElementInViewport(el) {
var top = el.offsetTop;
var left = el.offsetLeft;
var width = el.offsetWidth;
var height = el.offsetHeight;
while(el.offsetParent) {
el = el.offsetParent;
top += el.offsetTop;
left += el.offsetLeft;
}
return (
top < (window.pageYOffset + window.innerHeight) &&
left < (window.pageXOffset + window.innerWidth) &&
(top + height) > window.pageYOffset &&
(left + width) > window.pageXOffset
);
}
var listOfPanels = $('#item2, #item2, #item3, #item4, #item5');
$(window).scroll(function(event) {
if (listOfPanels.length){
listOfPanels.each(function(){
if (isElementInViewport($(this)[0])) {
console.log($(this).attr('id') + ' in viewport');
}
});
}
});
(isElementInViewport js method brought from: How to tell if a DOM element is visible in the current viewport?)
hope that helps.

Drag image javascript

here is two events. With first event:drag gets element id.
Second event: drop must move picture where is cursor, but not doing it...
Please help me to correct that drop event.. I know I can use jquery, but I just have little time.
I just somehow need in drop event where is if((parseInt(id, 10) > 0) || (id==0)) change picture cords, but i dont know what to use.
part of code is here:
function drop(ev)
{
ev.preventDefault();
var id=ev.dataTransfer.getData("id");
var CursorY=ev.pageY;
var CursorX=ev.pageX;
var posx = 0;
var posy = 0;
if (ev.pageX || ev.pageY) {
posx = ev.pageX;
posy = ev.pageY;
}
else if (ev.clientX || ev.clientY) {
posx = ev.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
posy = ev.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
var element = document.getElementById(id);
var element2 = document.getElementById("insert_box");
var name = element.getAttribute("name");
var w=document.getElementById(id).offsetWidth;
var h=document.getElementById(id).offsetHeight;
//alert(w+" "+h )
if((parseInt(id, 10) > 0) || (id==0))
{
//element.style.top=posy;
//element.style.left=posx;
}else
{
element2.innerHTML = element2.innerHTML + "<div class='drag'><img style='position:absolute' draggable='true' name="+name+" id='"+i+"' ondragstart='drag(event)' src='Images/"+name+"'></div>";
var element_ID = document.getElementById(i);
i++;
}
}
All code here:
http://pastebin.com/MwaVpzL5
Here is picture:
where is left you can drag image into box in right and when creates new image and when I need to move created image
if your able to use jquery then it will make you life an aweful lot easier as jqueryui has several methodsof use
jqueryui draggable will do your dragging and droppable will do your targets

How to remove selected image on a div when you click on it?

I am fairly new to Javascript and would like to create a div whereby it allows a person to define points on it by clicking on the area within the div. An image will be added to represent the point clicked. Thereafter, if the person wants to remove this point, upon clicking on the image, it should be remove.
I have done the part whereby it allows a person to define the points based on a minor modification to an existing fiddle: http://jsfiddle.net/uKkRh/1/
Reference: jquery how to add pin to image and save the position to SQL
I also manage to remove all the images by click on the button.
However, I am still short of how to remove the image from the div when the person clicks on the image.
I have tried the following:
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
but it works itermitently.
Please see my JSfiddle for my sample. http://jsfiddle.net/WindSaviour/rUNsJ/19/
var point = [];
var id = 0;
$(document).ready(function() {
var output = $('#container');
$("#container").click(function(e) {
e.preventDefault();
var isPointPresent = false;
var x = e.pageX - this.offsetLeft;
var y = e.pageY - this.offsetTop;
console.log("Mouse Click Pos (x=" + x + ", y=" + y + ")");
for(var i=0; i< point.length; i++) {
if(x >= point[i].min_x && x<=point[i].max_x) {
if(y >= point[i].min_y && y<=point[i].max_y) {
isPointPresent = true;
point.splice(i,1);
break;
}
}
}
point[point.length] = { "x-pos": x, "y-pos":y, "min_x": x-25, "max_x": x+25, "min_y": y-83, "max_y": y};
if(isPointPresent) {
$('#container >img').click(function() {
var selectedImg = $(this);
selectedImg.remove();
return;
});
}
var img = $('<img>');
var left = x-25;
var top = y-83;
console.log("Img Start Pos (x=" + left + ", y=" + top + ")");
img.css('top', top);
img.css('left', left);
img.attr('src', 'http://www.clker.com/cliparts/P/w/G/0/N/o/google-map-th.png');
img.attr('id', id);
img.appendTo('#container');
/*
*/
id++;
})
});
$('#remove').click(function() {
$('#container > img').remove();
});
Try this http://jsfiddle.net/uKkRh/635/, but you need a newer verion of jQuery
$('#container').on('click', 'img', function (e) {
e.stopPropagation();
$(this).remove();
});

draggable without jQuery ui

How to make a element draggable without using jQuery UI?
I have this code:
<script type="text/javascript">
function show_coords(event)
{
var x=event.clientX;
var y=event.clientY;
var drag=document.getElementById('drag');
drag.style.left=x;
drag.style.top=y
}
</script>
<body style="height:100%;width:100%" onmousemove="show_coords(event)">
<p id="drag" style="position:absolute">drag me</p>
</body>
The problem is that I want to drag while the user the pressing the mouse button. I tried onmousedown but results were negative.
It will be quite easy as you get the concept.
function enableDragging(ele) {
var dragging = dragging || false, //Setup a bunch of variables
x, y, Ox, Oy,
enableDragging.z = enableDragging.z || 1,
current;
ele.onmousedown = function(ev) { //When mouse is down
current = ev.target;
dragging = true; //It is dragging time
x = ev.clientX; //Get mouse X and Y and store it
y = ev.clientY; // for later use.
Ox = current.offsetLeft; //Get element's position
Oy = current.offsetTop;
current.style.zIndex = ++enableDragging.z; //z-index thing
window.onmousemove = function(ev) {
if (dragging == true) { //when it is dragging
var Sx = ev.clientX - x + Ox, //Add the difference between
Sy = ev.clientY - y + Oy; // 2 mouse position to the
current.style.top = Sy + "px"; // element.
current.style.left = Sx + "px";
return false; //Don't care about this.
}
};
window.onmouseup = function(ev) {
dragging && (dragging = false); //Mouse up, dragging done!
}
};
}
enableDragging(document.getElementById("drag")); //draggable now!
var ele = document.getElementsByTagName("div");
for(var i = 0; i < ele.length; i++){ //Every div's is draggable
enableDragging(ele[i]); // (only when its "position"
} // is set to "absolute" or
// "relative")
http://jsfiddle.net/DerekL/NWU9G/
The reason why your code is not working is because the <div> will always follow where your cursor goes, and you are not actually dragging it. The top left corner will always follow your cursor, and this is not we wanted.
UPDATE
Now if you only want a grabber or something similar, just change this part of the script:
ele.onmousedown = function(ev) {
current = ev.target;
to
var grabber = document.createElement("div");
grabber.setAttribute("class", "grabber");
ele.appendChild(grabber);
grabber.onmousedown = function(ev) {
current = ev.target.parentNode;
Now you can only click on the grabber to start the dragging process.
http://jsfiddle.net/DerekL/NWU9G/7/

Categories