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

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

Related

Moving randomly placed boxes with the mouse

I have created a program that populates the canvas with randomly positioned boxes with random colors. That part was easy, problem im having is that I would like to move any of these colored boxes around with my mouse. As well, the pointer must stay a costant distance from the top-left corner. My code is below, any help would be greatly appreciated!
window.onload = init;
function init() {
var x= Math.floor(Math.random()*400);
var y= Math.floor(Math.random()*400);
var body = document.getElementsByTagName("body")[0];
var canvas = document.createElement("canvas");
canvas.height = window.innerHeight;
canvas.width = window.innerWidth;
var context = canvas.getContext("2d");
// Repeat to draw a rectangle 100 times
for(var i=0;i<100;i++){
var color = '#'+ Math.round(0xffffff * Math.random()).toString(16);
context.fillStyle = color;
//Each rectangle is at (0 ~ width of window, 0 ~ height of window)
//Each rectangle's size is 50x50)
context.fillRect(Math.random()*window.innerWidth,
Math.random()*window.innerHeight, 50, 50);
}
document.body.appendChild(canvas);
}
var mousePiece = null;
function init2() {
//we are grabbing the div elm by uts id
// var divEl = document.getElementById("ace");
var cx = document.querySelector("canvas").getContext("2d");
//divEl.style.top = getStyle(divEl,"top");
//divEl.style.left = getStyle(divEl,"left");
addEvent(cx, "mousedown", mouseGrab, false);
}
function mouseGrab(e) {
var evt = e || window.event;
mousePiece = evt.target || evt.srcElement;
addEvent(document, "mousemove", mouseMove, false);
addEvent(document, "mouseup", mouseDrop, false);
}
function mouseMove(e) {
var evt = e || window.event;
var mouseX = evt.clientX;
var mouseY = evt.clientY;
mousePiece.style.left = mouseX + "px";
mousePiece.style.top = mouseY + "px";
}
function mouseDrop(e) {
mousePiece = null;
removeEvent(document, "mousemove", mouseMove, false);
removeEvent(document, "mouseup", mouseDrop, false);
}
function addEvent(object, evName, fnName, cap) {
if (object.attachEvent)
object.attachEvent("on" + evName, fnName);
else if (object.addEventListener)
object.addEventListener(evName, fnName, cap);
}
function removeEvent(object, evName, fnName, cap) {
if (object.detachEvent)
object.detachEvent("on" + evName, fnName);
else if (object.removeEventListener)
object.removeEventListener(evName, fnName, cap);
}
function getStyle(object, styleName) {
if (window.getComputedStyle) {
return document.defaultView.getComputedStyle(object,
null).getPropertyValue(styleName);
} else if (object.currentStyle) {
return object.currentStyle[styleName]
}
}
I would consider JQuery UI draggable. I made you a JS Fiddle with random colors and all. There are many things you can do with JQuery UI so check the docs to find exactly what you need.
$( document ).ready( function () {
for ( var i = 0; i < 50; i++ ) {
var randomColor = Math.floor(Math.random()*16777215).toString(16);
var ranNum = Math.round( Math.random() * 65 )
$( ".boxHolder" ).append( '<div class="pos' + i + ' draggable ui-widget-content"></div>' )
$( ".pos" + i ).css({
"background" : "#" + randomColor,
"top" : 10 * i + "px",
"left" : ranNum * 6 + "px"
})
}
})
$( function() {
$( ".draggable" ).draggable()
})
The bad news is that the canvas element is a pixel map: when you draw something on it, you modify pixel values as if you were updating an image. Drawing on the canvas does not create HTML elements that can be assigned an id, grabbed, or moved around using event.target (the target in your case will be the canvas element).
The good news is that there are canvas libraries that create an object model on top of the canvas for items separately placed and then allow you to move them around. For example have a look at fabric.js for demonstrations of the operations it supports. Feel free to do more research on your options!
Also note two issues with the random color string:
Use Math.floor instead of Math.round to avoid ending up with a value of 2^24 (also corrected in ALFmachine's reply)
Defining CSS colors usig a hex digit string requires either 3 or 6 hex digits preceeded by '#'. To avoid color values being discarded by the CSS parser in your case, lead fill the hex digits with '0' to make up the 6 digits as required.
You could construct a CSS rbg() color string using three random integers in range 0 to 255 as the alternative.

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?

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

Getting mouse position in keyboard event

I'm trying to have a selection wheel appear when the user holds down the Shift key.
The wheel should be centred on the mouse's position.
However when I test this, pageX and clientX are both undefined on the event object.
Is it possible to get the mouse coordinates on a keyboard event?
No, simply track mousemove events and continuously save the current position in case you get a keyboard event.
Cache mouse position in a global variable in every mousemove event and use it when a key event fires:
var mousePosition = {x:0, y:0};
$(document).bind('mousemove',function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
});
$(document).bind('keyup', function(keyUpEvent){
$('body').append($('<p/>').text('x:' + mousePosition.x + ' * y: ' + mousePosition.y));
});
JSBIN: http://jsbin.com/uxecuj/4
JavaScript without jQuery:
var mousePosition = {x:0, y:0};
document.addEventListener('mousemove', function(mouseMoveEvent){
mousePosition.x = mouseMoveEvent.pageX;
mousePosition.y = mouseMoveEvent.pageY;
}, false);
document.addEventListener('keyup', function(keyUpEvent){
var divLog = document.querySelector('#log'),
log = 'x:' + mousePosition.x + ' * y: ' + mousePosition.y,
p = document.createElement('p').innerHTM = log;
divLog.appendChild(p);
}, false);
Here's the POJS equivalent of other answers that is cross browser back to IE 6 (and probably IE 5 but I don't have it to test any more). No global variables even:
function addEvent(el, evt, fn) {
if (el.addEventListener) {
el.addEventListener(evt, fn, false);
} else if (el.attachEvent) {
el.attachEvent('on' + evt, fn);
}
}
(function () {
var x, y;
window.onload = function() {
addEvent(document.body, 'mousemove', function(e) {
// Support IE event model
e = e || window.event;
x = e.pageX || e.clientX;
y = e.pageY || e.clientY;
});
// Show coords, assume element with id "d0" exists
addEvent(document.body, 'keypress', function() {
document.getElementById('d0').innerHTML = x + ',' + y;
});
}
}());
But there are bigger issues. Key events are only dispatched if an element that can receive keyboard input is focused (input, textarea, and so on). Also, if the user scrolls the screen without moving the mouse, the coordinates will probably be wrong.
An alternative solution is to use CSS to replace the cursor with a custom animation.
If you're using jQuery, you can do the following (assuming you have an image with id="wheelImage" and whose position is set to absolute), write the following inside your keydown event. Here we use the global properties pageX and pageY that are passed to any handler. You can also use jQuery's shiftKey property to check if the shift key has been pressed.
$().keydown(function(e) {
if (e.shiftKey) {
e.preventDefault();
$('#wheelImage').css('left',e.pageX ).css('top', e.pageY);
}
});
Cache the mouse position.
var x = 0, y = 0;
document.addEventListener('mousemove', function(e){
x = e.pageX
y = e.pageY;
}, false);
document.addEventListener('keyup', function(e){
console.log(x + ' ' + y);
}, false);
Or with JS Ninja Library.
var x = 0, y = 0;
$(document).mousemove(function(e){
x = e.pageX
y = e.pageY;
});
$(document).keypressed(function() {
console.log(x + ' ' + y);
});

onMouseMove get mouse position [duplicate]

This question already has answers here:
How to get mouse position in jQuery without mouse-events?
(7 answers)
Closed 3 years ago.
In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?
if you can use jQuery, then this will help:
<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
$("#divA").mousemove(function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
$("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
});
</script>
here is pure javascript only example:
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
document.Show.MouseX.value = tempX;//MouseX is textbox
document.Show.MouseY.value = tempY;//MouseY is textbox
return true;
}
This is tried and works in all browsers:
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
Now you can use it in an event like this:
document.onmousemove=function(e) {
var mousecoords = getMousePos(e);
alert(mousecoords.x);alert(mousecoords.y);
};
NOTE: The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.
function getMousePos(e) {
return {
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop
};
}
It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:
var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
.on('mousemove', function()
{
coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
// the top of the page (because I selected
// 'html')
});
In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html' with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').
Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-
var whereAt= (function(){
if(window.pageXOffset!= undefined){
return function(ev){
return [ev.clientX+window.pageXOffset,
ev.clientY+window.pageYOffset];
}
}
else return function(){
var ev= window.event,
d= document.documentElement, b= document.body;
return [ev.clientX+d.scrollLeft+ b.scrollLeft,
ev.clientY+d.scrollTop+ b.scrollTop];
}
})()
document.ondblclick=function(e){alert(whereAt(e))};

Categories