Hi I am trying to place a div in the center of my mouse course when I click a link
I have something like
<a id='btn' href='#' ><img src='test.png' /></a>
I want to see the new div overlay on my test.png and I want my mouse curse be the center vertically and horizontally of the new div.
My js
var contentDiv = document.createElement('div');
var img = document.createElement('img');
contentDiv.setAttribute('class','test1');
img.src='newimg.png';
contentDiv.appendChild(img);
$("#btn").on('click', function(e){
$('body').append(contentDiv)
var w = $(contentDiv).width()/2
var h = $(contentDiv).height()/2
var x = e.pageX - h //- $(this).offset().left;
var y = e.pageY - w //- $(this).offset().top;
$(contentDiv).css({top: y, left: x, 'transform': 'scale(.2)'})
e.preventDefault();
})
My code won't put my mouse cursor as the center of the new div. Can anyone help me about it? Thanks so much!
Try
var x = e.pageX - w
var y = e.pageY - h
Example
That's the jQuery way to get the mouse position (e.pageX), so you could also do:
var x = e.clientX - w;
var y = e.clientY - h;
Example
That's the pure-JS way.
Your problem was you were subtracting height from x and width from y, while it should be the other way around. Remember, x is left and right, y is up and down. In computer science, up decreases y, and down increases y, right increases x, left decreases x.
Don't get them mixed up.
Related
I'm trying to position the center of a div element to the center of the mouse cursor, that will follow along its movements.
Already I came up with the code below, but the problem with this one is, that the following div is not positioned at the center of my cursor, but with some offset off the cursor.
WORKFLOW
The basic idea behind my code is, when the mouse enters the .post-entry div element, the .pointer within the current item should be displayed and follow the cursor of the mouse. When the mouse leaves the div it should be hidden.
CODE
HTML post item:
<article class="col-md-4 col-sm-6 post-entry">
<a href="#" title="">
<figure class="post-thumb">
<img src="http://placehold.it/300x300" alt="">
<div class="pointer" style="background: red;"></div>
</figure><!-- End figure.post-thumb -->
</a>
</article><!-- End article.col-md-4 post-entry -->
JS:
$('.entry .post-entry').each(function() {
$(this).on("mouseenter", mouseEnter);
$(this).on("mousemove", mouseMove);
$(this).on("mouseleave", mouseLeave);
});
function mouseEnter(event) {
console.log('enter');
var target = $(this);
var dot = target.find('.pointer');
var mX = (event.clientX);
var mY = (event.clientY);
set(
dot, {
x: mX,
y: mY,
force3D: !0
}
);
};
function mouseMove(event) {
console.log('move');
var target = $(this);
var dot = target.find('.pointer');
// var offset = target.offset();
// var width = target.width();
// var height = target.height();
// var top = offset.top;
// var left = offset.left;
var mX = (event.clientX);
var mY = (event.clientY);
$(dot).css('-webkit-transform', 'translate3d(' + mX + 'px, ' + mY + 'px, 0)');
};
function mouseLeave(event) {
console.log('leave');
var target = $(this);
var dot = target.find('.pointer');
$(dot).css('-webkit-transform', 'translate3d(0, 0, 0) scale(0, 0)');
};
function onClick(event) {
event.preventDefault();
console.log('click');
};
function set(el, obj) {
var dot = $(el).css('-webkit-transform', 'translate3d(' + obj.x + 'px, ' + obj.y + 'px, 0px)');
return dot;
};
PROBLEM / DEMO
As mentioned before, the span is following the mouse cursor, only the span is not positioned to the center of the cursor. It will be offset the mouse. See live demo here
I tried already something like this for the mX and mY variables, but with no succes:
var mX = (event.clientX - $(this).offset().left) / $(this).width() * $(this).width() - .125 * $(this).width();
var mY = (event.clientY - $(this).offsetTop) / $(this).height() * $(this).height() - .125 * $(this).width();
Also the answer from #hiEven doesn't work and will let me with the same issue:
transform: calc(mX - 50%, mY - 50%)
I know I should do something with dividing the .pointer by half, but how I should implement that in the code is a big question mark for me.
UPDATE
I created two new Codepen projects:
Use without images: http://codepen.io/anon/pen/GqGOLv. When you hover over the first item you will see that the brown pointer is correctly following your mouse cursor - what I am looking for. But when hovering over the second one, you will see the red pointer, only when you are at the very left side of the item.
When I use images: http://codepen.io/anon/pen/QExOkx. The problem by this example is that when you at the very top of the first column, you will see the brown pointer. When hover at the top left corner of the second item you will see a little piece of the red pointer, the same as the example without images.
Both pointer should follow the mouse cursor correctly. And I am searching for a solution that works with the use of an image.
Beside these two examples, when I add to the first one, an extra margin-left to the first item, the brown pointer will not be in the center of the mouse cursor, only when it's set to margin-left zero.
So I don't know what's missing and why it only works with the first example (without images) and only for the first item?
Try the code below
<html>
<head>
<style>
#mouse_div{
position: absolute;
background-color: black;
}
</style>
<script>
var div_width = 100;
var div_height = 100;
var div_x, div_y;
function mouse_position(event){
var mouse_x = event.clientX;
var mouse_y = event.clientY;
document.getElementById("mouse_div").style.width = div_width + "px";
document.getElementById("mouse_div").style.height = div_height + "px";
div_x = mouse_x - (div_width / 2);
div_y = mouse_y - (div_height / 2);
document.getElementById("mouse_div").style.left = div_x + "px";
document.getElementById("mouse_div").style.top = div_y + "px";
}
</script>
</head>
<body onmousemove="mouse_position(event)" onload="mouse_position(event)">
<div id="mouse_div"></div>
</body>
</html>
This program gets the position of your mouse, the width, and the height of the div. Then, it takes the x and subtracts the div's width divided by two from it (this centres the div's x position on your mouse). The program then does the same thing for the mouse y. Once all of the variables are defined, I use JavaScript to access the CSS of the div to place the div where it needs to be.
Note: you must make sure that the position of the div is set to absolute or the program will not work.
I assume you want the circle being center of your mouse, right?
try do this
transform: `translate(calc(${mx}px - 50%), calc(${my}px - 50%))
here is the demo
Based on my latest update, I did not conform to the correct formula that is needed to center the element .pointer to the mouse.
In order to use the following calculation within mouseMove:
var mX = (event.clientX);
var mY = (event.clientY);
Should be changed to this:
var height = dot.height();
var width = dot.width();
var offset = target.offset();
var w = target.width();
var h = target.height();
var top = offset.top;
var left = offset.left;
var mX = (event.clientX - left) - width / 2 - 15; // 15 = padding
var mY = (event.clientY - top) - height / 2;
So this formule is considering that the following DOM element .pointer will follow the mouse movements of the user. I don't know exactly why this working, but the offset from the previous item will be decreased from the current clientX coordinates, so the position of the second item is reset to zero, so the pointer will start at the left side of each item.
Here is a working demo of above code: http://codepen.io/anon/pen/AXdxZO?editors=0110
I have a div with a background image - the div is set to the exact size of the image and my pointer is set to a crosshair over the div.
I want to mark each click with its x and y positions in the div over the image background. This I can do but the mark on the div is always lower and to the left of the actual cursor why is this?
function showClick(x,y)
{
$('.clickable').append('<span id="'+x+y+'_span" style="position: absolute;top:'+y+'px;left:'+x+'px;" class="red">+</span>');
}
$('.clickable').bind('click', function (ev) {
var $div = $(ev.target);
var offset = $div.offset();
var xMargin = ($div.outerWidth() - $div.width()) / 2;
var yMargin = ($div.outerHeight() - $div.height()) / 2;
var x = (ev.pageX + xMargin) - offset.left;
var y = (ev.pageY + yMargin) - offset.top;
showClick(x,y);
});
working example: https://jsfiddle.net/b94ypmae/3/
You are not taking into account the size of the span (and the character inside it).
Your code is working properly, in that a span is being placed in your div at the position of your cursor, but that position is based on the upper left corner
If you put a border around your span you can see it is a perfect alignment of your upper left corner: JSFiddle showing border
You could fix this by taking into account the size of the placed span(if you know it will always be the same you could hard code it as well). Here's an example of getting the size of the placed span and moving it by half it's width and height: Fixed JSFiddle
var placedSpan = $("#" + x + y + "_span");
var width = placedSpan.width();
var height = placedSpan.height();
placedSpan.css('left', x - width / 2 + 'px');
placedSpan.css('top', y - height / 2 + 'px');
I have a box with a width of 800 and height of 600.
Then my screen size (container) is 1000 and its height is 700.
then, if we say:
x = container
y = rectangle
z = point in space
The engine only outputs the z based on its coordinate in x, therefore I need to calculate the coordinate of z in y.
I have:
z
size of x
size of y
coordinate of z in x
and what I want?
coordinate of z in y
Click for Demo
Jquery
$("#id").click(function(e){
var parentOffset = $(this).parent().offset();
//or $(this).offset(); if you really just want the current element's offset
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
});
Html
<div id="id">
//or $(this).offset(); if you really just want the current element's offset
</div>
Demo Link
It gives co-ordinates only for related container
Here is Script
$(document).ready(function(){
$("#container").click(function(e){
alert(e.pageX - $("#container").parent().offset().left);
alert( e.pageY - $("#container").parent().offset().top);
});
});
How can I make the windows scrollbar's Y coordinate be the same as the mouse Y coordinate, how
can I make the scrollbar follow the mouse?
The most compute efficient using way of doing this utilizing DOM-L3:
//HTML BLOCK
<canvas onmousemove="TrackMouse(event)"></canvas>
//JS BLOCK
function TrackMouse(e){
window.scrollBy(e.webkitMovementX, e.webkitMovementY);
}
Here is a jQuery-free solution:
var height = document.documentElement.scrollHeight;
function scroll(event){
var y = event.clientY;
var yPercentage = y/screen.height;
window.scrollTo(0,yPercentage*height);
}
window.onmousemove = scroll;
In action: http://jsfiddle.net/xF2vs/3/
On a real page, if your mouse is at the bottom of the screen, the page will be scrolled entirely to the bottom. For some reason in jsfiddle it doesn't quite make it.
What it is doing is finding how far down your mouse is on the screen and scrolling the document down that same percent.
Sharing my modified version Nile's reply to get a version that scrolls both X and Y.
var height = document.documentElement.scrollHeight;
var width = document.documentElement.scrollWidth;
function scroll(event) {
var y = event.clientY;
var x = event.clientX;
var yPercentage = y / screen.height;
var xPercentage = x / screen.width;
window.scrollTo(xPercentage * width, yPercentage * height);
}
window.onmousemove = scroll;
To scroll just the width, but not the height (as Murplyx requested a year ago) use the following:
var width = document.documentElement.scrollWidth;
function scroll(event) {
var x = event.clientX;
var xPercentage = x / screen.width;
window.scrollTo(xPercentage * width, 0);
}
window.onmousemove = scroll;
Thank you Nile for the start!
I was just messing around in jsfiddle trying to resize a box base on the mouse position. Making the box larger as the mouse moves away is simple, just get the distance. However, I want to do the opposite; I want the box to increase in size as the mouse gets closer and decrease as the mouse moves away. I haven't been able to think up any formulas for this. I feel there could be something really simple that I am missing.
<div id="box"></div>
#box {
height: 100px;
width: 100px;
background: black;
}
var box = document.getElementById('box');
// center point of the box
var boxX = 50;
var boxY = 50;
document.addEventListener('mousemove', function(e) {
var x = e.pageX,
y = e.pageY;
var dx = x - boxX,
dy = y - boxY;
var distance = Math.sqrt(dx *dx + dy * dy);
box.style.width = box.style.height = distance + 'px';
}, false);
Here is a link to the fiddle:
http://jsfiddle.net/gSDPq/
Any help is appreciated, Thanks
Try distance = Math.max(0,200-Math.sqrt(dx*dx + dy*dy));
This should have the box disappear when the mouse is 200px or more away, and steadily grow to 200px in size as you get nearer the middle. Adjust numbers as needed (for instance, divide the Math.sqrt() part by 2 to reduce the effect that distance has, or adjust the 200 to affect the max size)
jsfiddle
var box = document.getElementById('box');
// center point of the box
var boxX = 50;
var boxY = 50;
var ux=500, uy=500;// 1.stage
document.addEventListener('mousemove', function(e) {
var x = e.pageX,
y = e.pageY;
var dx = ux-(x - boxX),
dy = uy-(y - boxY);// 2.stage
var distance = Math.sqrt(dx *dx + dy * dy);
box.style.width = box.style.height = distance + 'px';
}, false);
I'm not sure that Kolink's answer actually did what you wanted to do. You seem to want the box to grow when the mouse is getting closer to it.
Just subtracting both x and boxX from some predefined box size value should do that:
var dx = 400 - x - boxX,
dy = 400 - y - boxY;
if(dx<0) dx = 0;
if(dy<0) dy = 0;
http://jsfiddle.net/gSDPq/3/