Drag image javascript - 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

Related

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.

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

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?

Typing in autoresizing textarea keeps on focusing at the top of the element

I have an expanding textarea. When the textarea has already expanded enough to reach the bottom of the window, the body flickers/scrolls back to the top of the textarea and you cannot see the last characters you've keyed in unless you scroll the window.
The sample can be found in this jsfiddle. I tried adding a scrollTo to the body
window.scrollTo(0, document.getElementsByTagName('textarea')[0].getBoundingClientRect().bottom);
How can I calculate the offset of the cursor in textarea from the window? I was thinking of getting the top offset of the cursor and just scrolling the window to its position if the cursor is already beyond the fold.
Help on this would be greatly appreciated :)
your code is great - i just added some milliseconds of timeout (around 100-200 is enough) and now it behaves nicely. Just wondered what that on('focus') event handler is for. And guess you can skip calling focus() in resize() function...
I found a solution right here in stack! https://stackoverflow.com/a/18262927/769326
I added the code snippet found there in the resize function also.
function resize(e){
var text = _this.value,
lines = text.split('\n'),
cursorPosition = $this.getCursorPosition(),
scrollLeft = window.pageXOffset || (document.documentElement || document.body.parentNode || document.body).scrollLeft,
scrollTop = window.pageYOffset || (document.documentElement || document.body.parentNode || document.body).scrollTop;
for(var i = 0, length = lines.length; i < length; i++){
if(lines[i].length <= settings.charactersPerLine){
continue;
}
var j = 0,
space = settings.charactersPerLine;
while(j++ <= settings.charactersPerLine){
if(lines[i].charAt(j) === ' '){
space = j;
}
}
lines[i+1] = lines[i].substr(space) + (lines[i + 1] || '');
lines[i] = lines[i].substr(0, space);
}
_this.value = lines.join('\n');
if(cursorPosition == text.length){
setCaretToPos(_this, cursorPosition + 1);
}
else{
setCaretToPos(_this, cursorPosition);
}
_this.style.height = elementHeight;
_this.style.height = _this.scrollHeight + 'px';
_this.style.overflow = 'hidden';
window.scrollTo(scrollLeft, scrollTop);
}
here's the jsfiddle
I use the following for ALL mouse position issues and have never had a problem. I don't see why it wouldn't work for this instance aswell.
var cX;
var cY;
document.onmousemove = function(e){
cX = e.pageX;
cY = e.pageY;
}
You could use it like I have:
window.scrollTo(0, cX);
Or simply put the e.pageX into your code example. cX, cY are cursor coordinates.

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

Javascript/jquery, get all divs location at (x,y). Forwarding touches? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get a list of all elements that resides at the clicked point?
I know I can get the element with the highest z-index by using document.elementFromPoint(x,y).
The problem is I need to get every div that contains the touch event's location.
How can I propagate touches to elements underneath?
I have seen some hacky solutions that show/hide elements while re-generating the event, or pointer-events style with css, however I cannot use these and they may cause flickering...
The following diagram illustrates what I need to do:
If the purple, green, and blue boxes represent the div elements, and the red dot is the touch location, I need a function that would return "div3, div2, div1".
No flickering with this code:
$("body").click(function(e){
var x = e.pageX, y = e.pageY;
var res = [];
var ele = document.elementFromPoint(x,y);
while(ele && ele.tagName != "BODY" && ele.tagName != "HTML"){
res.push(ele);
ele.style.display = "none";
ele = document.elementFromPoint(x,y);
}
for(var i = 0; i < res.length; i++){
res[i].style.display = "";
}
console.log(res);
});​
What about doing:
$(document).click(function(e) {
var pageX = e.pageX;
var pageY = e.pageY;
$('*').each(function(index) {
var offset = $(this).offset();
var left = offset.left;
var right = offset.right;
var width = $(this).width();
var height = $(this).height();
if(pageX > left && pageX < left + width) {
if(pageY > top && pageY < top + height) {
//Handle the div
}
}
});
});

Categories