Javascript offset on positioning div to cursor position - javascript

I want to position a div to mouse position.
This is my pen: http://codepen.io/Linuxer4Fun/pen/QdJzWv
It does what it has to, but when I go to my browser, the div has an unnerving offset
I think, the problem is in here: I already tried pageX and clientX
document.onmousemove = function (e) {
cursor_x = e.clientX;
cursor_y = e.clientY;
}
This is how it looks on my pc:
HERE

Is it because the box stays where the cursor first entered the element? Try using the mousemove event to update the position of the box as the mouse moves.

Related

jQuery: Check if mouse is over an animation?

This is pretty much what I'm working on: https://jsfiddle.net/atg5m6ym/2625/
I'm animating a div with jQuery to move left, then logging to the console when I hover over the div and when I move my mouse away from it:
$("div").animate({left: '250px'}, 6000);
$('div').hover(function() {
console.log("Mouse hovered on div!");
}).mouseleave(function() {
console.log("Mouse left div!");
})
Naturally, the program will run console.log("Mouse hovered on div!"); once I put my mouse on the element.
However, if I leave my mouse idle and the animated element moves onto it, nothing in $('div').hover(function(){}) will run. I have to move my mouse onto the element for the code to run, not let the element come to the mouse.
The same thing also happens if I hover onto the element, and then leave my mouse idle. Nothing in $('div').mouseleave(function(){}) will run after the element leaves, until I move my mouse from its position.
Is there any way to work around this? I am working with animated divs and I need code to run even if the mouse is idle and the divs pass through it.
Manually take the mouse's last known position and compare it to the position of the circle. This is kind of extensive but it should get you the right results.
Here is a JSFiddle:
https://jsfiddle.net/3vpaoj59/
$("div").animate({left: '250px'}, 6000);
$(document).ready(function() {
// record down the position of the cursor
var cursorX;
var cursorY;
document.onmousemove = function(e){
cursorX = e.pageX;
cursorY = e.pageY;
}
// boolean to know if hovered or not, and to know whether to report in console.log
var hover = false;
// function to call by setinterval to check if mouse is within radius
function checkMouse(){
// find the centerpoint of the circle by taking its position then adding half its width/height to each coordinate
var left = $("#foo").offset().left+$("#foo").width()/2;
var top = $("#foo").offset().top+$("#foo").height()/2;
// use pythagorean theorem to find distance between two points
var xdist = Math.pow(Math.abs(cursorX - left),2);
var ydist = Math.pow(Math.abs(cursorY - top),2);
var hypotenuse = Math.round(Math.sqrt(xdist+ydist));
// check if the distance is less than radius
if(hypotenuse <= $("#foo").width()/2 && !hover){
// if true and not already reported true, report then fix
console.log("mouse hovered on div!");
hover = true;
} else if (hypotenuse > $("#foo").width()/2 && hover){
// if false and not already reported false, report then fix
console.log("mouse left div!");
hover = false;
}
}
// repeatedly call this
setInterval(checkMouse, 100);
});
I changed the div's ID to "foo" for convenience. Make sure to do this as well so that the code works for your project, or modify the JS to not use "foo".
Explanation:
The reason why your problem was occurring was because your mouse's coords are only updated every time you move your cursor, and that's when hover states are checked by .hover. As such, we need to emulate the event that determines hover and call it repeatedly even when the cursor hasn't moved to make sure the hover state is updated.

Client X/Y on Chrome (Android)

I wish to retrieve the exact X/Y coordinates where the user has pressed on the screen. The coordinates must be the same no matter what level of zoom or scroll is applied. I am using event.clientX and event.clientY to retrieve these coordinates and this behaves as expected. The code is basically as follows:
$("#canvas").touchstart(function(e){
e.preventDefault();
var Y_LIMIT = 100
if(e.clientY <= Y_LIMIT){
... do stuff
}
});
A textarea is present on the screen with a submit button to allow the user to enter text. The issue is after the tablet focuses in on the textarea and the user enters text the clientX and clientY coordinates permanently change. I wish for the values to stay the same regardless of this operation.
Is there any way to keep clientX and clientY consistent even after entering text into a textarea or input box ?
Despite the fact that there is still a question left about how clientX & clientY have changed(did they descrease or increase their values?)
If they descreased their values you could give this a try to take the absolute position of a parent HTML element(DIV?) in which your textarea is located into consideration:
Check out this answer that answers about how to get absolute position of a HTML element:
// get absolut position of an HTML element
function cumulativeOffset (element) {
var top = 0, left = 0;
do {
top += element.offsetTop || 0;
left += element.offsetLeft || 0;
element = element.offsetParent;
} while(element);
return {
top: top,
left: left
};
};
// event handler callback function to retrieve client position
function funcToGetClientCoords(evt){
var area = document.getElementById("parentDIVId");
var absoluteViewportPos = cumulativeOffset(area);
return {
x: evt.clientX + absoluteViewportPos.left,
y: evt.clientY + absoluteViewportPos.top
};
}
I did not prove this but it sounds to me as if clientX & clientY coords changed according to your relative screenview position and when you click onto a textarea you automatically zoom into this textarea and so clientX and clientY coords might be descreased.
Another try could be to remember the absolute position of your parent DIV at the beginning and when interacting with your textarea add this position to clientX/clientY positions.
Hope this helps.

Dragging of element goes wrong when the container is scrolled

In this Fiddle, I made the red container draggable. As you can see, this is working fine but when the green container (parent container) is scrolled a bit and then the red container is dragged, the dragging is not happening at correct position.
Can someone please tell me what could be the problem?
I tried e.pageX, e.clientX and e.offsetX but still couldn't able to fix this. (or maybe I missed something)
You need to add the scrolling top position to your shape. If you want your square stay on the correct position check that:
function repositionShape(e) {
$self = repositionStart.self;
$commentSection = repositionStart.commentSection;
var dy = $('.wrapper').scrollTop(); // Get wrapper scroll position
$self.css({
'left': e.clientX - repositionStart.offset.left,
'top': e.clientY - repositionStart.offset.top +dy // Add delta to your square position
});
}

jQuery drag very wide div horizontally

Hi I've got this wide div, that I'd like to be able to drag horizontally, for a metro style interface.
http://jsfiddle.net/hwvvu2rg/7/
var el_w = $('.draggable').outerWidth();
$('#guide').on("mousemove", function(e) {
if ($dragging) {
$('#guide').offset({
left: e.pageX - el_w / 2
});
}
Currently everytime you mousedown, it resets to the first position, how do I adjust the maths so that each time you drag it uses the current position, so you can drag it along?
You can capture the relative position on mousedown (such as e.pageX - (parseInt($(this).css('left')) || 0)), try this:
http://jsfiddle.net/hwvvu2rg/9/

Hover event on div under absolute positioned div

Is possible to obtain hover event on element, which is under absolute positioned div? That absolute positioned div is child of body element, but that under isn't, so they are not in relationship parent/child. I do drag and drop of that absolute div and i want highlight area, where user can drop, when mouse it's under that area.
enter code here
http://jsfiddle.net/Rv8kp/
Short answer would be no, you cant. But.. there is a workaround
You can add mousemove event handler for the whole document. Inside the handler you check if mouse position is in the area of the element you need to hover.
var $pos = $("#pos");
var top = $pos.offset().top;
var left = $pos.offset().left;
var bottom = top + $pos.height();
var right = left + $pos.width();
$(document).mousemove(function (e) {
if (e.pageY >= top && e.pageY <= bottom && e.pageX >= left && e.pageX <= right)
$pos.addClass("hover");
else
$pos.removeClass("hover");
});
you can view full working example here

Categories

Resources