mouseX and mouseY only detect diagonal coordinates - javascript

I am tying the placing of an input box to the mouseX and mouseY coordinates, but my issue is that when I click I can only click in a small diagonal field across the body. I want it so that I can click anywhere on the body and it will go to that location. Any ideas on how to fix this peculiar problem?
<body onclick = "getLocation(event)">
<style>
html{
}
div{
display: block;
}
textarea, input {
clear: both;
position: relative;
}
textarea, input {
overflow: auto;
width: 20%;
}
</style>
<input id = "enter" placeholder = "input" style = "top:20;left:40;"></input>
</body>
<script>
function getLocation(event){
var y = event.clientY;
var x = event.clientY;
console.log("Y:" + y + " X:" + x);
document.getElementById("enter").style.left = x;
document.getElementById("enter").style.top = y;
}
</script>

You need to set the width and height of the body. You also need to set units on the positions and you most likely want to use pageX and pageY, not clientX and clientY
function getLocation(event){
var y = event.pageY;
var x = event.pageX ;
console.log("Y:" + y + " X:" + x);
document.getElementById("enter").style.left = x + "px";
document.getElementById("enter").style.top = y + "px";
}
document.body.addEventListener("click", getLocation);
html, body{
width:100%;
height:100%;
}
div{
display: block;
}
textarea, input {
clear: both;
position: relative;
}
textarea, input {
overflow: auto;
width: 20%;
}
<input id="enter" placeholder="input" style="top:20px;left:40px;"></input>

<script>
function getLocation(event){
document.getElementById('enter').style.left = (window.Event) ? event.pageX : event.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
document.getElementById('enter').style.top = (window.Event) ? event.pageY : event.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
}
</script>
Just replace this, and it works :)

Related

Setting dynamic position of element using Javascript instead of jQuery offset()

I can dynamically position a div element, so that as the user moves the mouse the element follows, using jQuery:
inputFile.offset({
top: ev.pageY - 15,
left: ev.pageX - 160
});
I would prefer to not use jQuery. How would I accomplish the same using vanilla JavaScript?
Define div to use then create a function for the X and Y coordinates and one for the cursor then have div follow cursor.
var div = 'mydiv'; // div that will follow the mouse. Set position:absolute in CSS
var offset_X = 10; // X offset from mouse position
var offset_Y = 10; // Y offset from mouse position
function mouseX(evt) { // create function for x mouse event
if (!evt) evt = window.event;
if (evt.pageX) return evt.pageX;
else if (evt.clientX) return evt.clientX + (document.documentElement.scrollLeft ? document.documentElement.scrollLeft : document.body.scrollLeft);
else return 0;
}
function mouseY(evt) { // create function for Y mouse event
if (!evt) evt = window.event;
if (evt.pageY) return evt.pageY;
else if (evt.clientY) return evt.clientY + (document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop);
else return 0;
}
function follow(cursor) { // create function for cursor
var obj = document.getElementById(div).style;
obj.left = (parseInt(mouseX(cursor)) + offset_X) + 'px';
obj.top = (parseInt(mouseY(cursor)) + offset_Y) + 'px';
}
document.onmousemove = follow; // call function when user moves mouse
#mydiv {
position: absolute;
display: block;
background: #ccc;
height: 100px;
padding: 20px 50px;
}
<div id="mydiv"> </div>

Move a div within another div

I am trying to develop a simple app.
When we drag the small box inside the bigger box, the smaller box should move inside the bigger box.
However, it can't go outside the bigger box. I know how to move the smaller box, but I don't know how to keep it inside the bigger box. Can somebody help me, please?
As I mentioned, my code moves the small box properly but does not keep it inside the bigger box.
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
guy.style.left =guy.offsetLeft + distX + "px";
guy.style.top = guy.offsetTop + distY + "px";
lastX = event.pageX;
lastY = event.pageY;
}
}
#container {
height:400px;
width:600px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:green;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:red;
left: 200px;
top: 200px;
}
<div id="container" draggable="true" ></div>
<div id="guy"></div>
You need to restrict guy's position to the container's bounds. In other words, guy's x position can at minimum be the container's x position, at maximum the container's x position plus the container's width minus guy's witdh. The same goes for the y axis, but with height instead of width.
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
var minX = cont.offsetLeft;
var maxX = minX + cont.offsetWidth - guy.offsetWidth;
var minY = cont.offsetTop;
var maxY = minY + cont.offsetHeight - guy.offsetHeight;
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
var targetX = guy.offsetLeft + distX;
var targetY = guy.offsetTop + distY;
guy.style.left = Math.min(maxX, Math.max(minX, targetX)) + "px";
guy.style.top = Math.min(maxY, Math.max(minY, targetY)) + "px";
lastX = event.pageX;
lastY = event.pageY;
}
}
#container {
height:200px;
width:300px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:green;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:red;
left: 100px;
top: 100px;
}
<div id="container" draggable="true" ></div>
<div id="guy"></div>

Dragover: Can't move to left and top

I have an element which I would like to move with the mouse.
var troll = document.getElementById('troll');
troll.addEventListener('dragover', (e) => {
e.preventDefault();
e.target.style.left = e.clientX + 'px';
e.target.style.top = e.clientY + 'px';
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>
From left to right and from top to bottom it works OK. Not perfect, since the very first move takes a whole space and it doesn't look smooth. But the main problem is that I can't move from right to left or from bottom to top.
Any help would be appreciated.
You wanna use drag not dragover, and some logic to know where you're going up or down or left or top.
var troll = document.getElementById('troll');
var X,Y = 0;
troll.addEventListener('drag', (e) => {
e.preventDefault();
if (e.clientX > X)
{
e.target.style.left = X + 'px';
}
else if (e.clientX < X)
{
e.target.style.left = X-- + 'px';
}
if (e.clientY > Y)
{
e.target.style.top = Y + 'px';
}
else if (e.clientY < Y)
{
e.target.style.top = Y-- + 'px';
}
X = e.clientX;
Y = e.clientY;
}, false);
img {
width: 100px;
cursor: pointer;
position: absolute;
}
<div id="troll">
<img src="http://images.mmorpg.com/features/7909/images/Troll.png" alt="Troll">
</div>

how to move one div with another in javascript

I am trying to make a web app with two boxes, one contained in the other. The user should be able to click and move the inner box, however, the user should not be able to move this box outside the confines of the outer box. The user can move the outer box by dragging the inner box against one of the edges of the outer box. I know how to move the inner box, but the problem is how to move the other box with this restriction. Can anybody help me please? Here is what I did so far:
<!doctype html>
<head>
<title>JavaScript Game</title>
<style>
#container {
height:400px;
width:600px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:green;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:red;
left: 200px;
top: 200px;
}
</style>
</head>
<body>
<div id="container"></div>
<div id="guy"></div>
<script>
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
guy.style.left =guy.offsetLeft + distX + "px";
guy.style.top = guy.offsetTop + distY + "px";
lastX = event.pageX;
lastY = event.pageY;
}
}
</script>
</body>
You could add a check to see if moving the box would break bounds of cont.
try to use getBoundingClientRect()
Check the snippet below for the working code.
View in full screen for best results.
var guy=document.getElementById("guy");
var cont=document.getElementById("container");
var lastX,lastY; // Tracks the last observed mouse X and Y position
guy.addEventListener("mousedown", function(event) {
if (event.which == 1) {
lastX = event.pageX;
lastY = event.pageY;
addEventListener("mousemove", moved);
event.preventDefault(); // Prevent selection
}
});
function buttonPressed(event) {
if (event.buttons == null)
return event.which != 0;
else
return event.buttons != 0;
}
function moved(event) {
if (!buttonPressed(event)) {
removeEventListener("mousemove", moved);
} else {
var distX = event.pageX - lastX;
var distY = event.pageY - lastY;
guy.style.left =guy.offsetLeft + distX + "px";
guy.style.top = guy.offsetTop + distY + "px";
// ********************************************************************
// get bounding box borders
var contBounds = guy.getBoundingClientRect();
var guyBounds = cont.getBoundingClientRect();
// check bottom bounds
if (contBounds.bottom >= guyBounds.bottom){
cont.style.top = cont.offsetTop + distY + "px";
}
// check top bounds
if (contBounds.top <= guyBounds.top){
cont.style.top = cont.offsetTop + distY + "px";
}
// check left bounds
if (contBounds.left <= guyBounds.left){
cont.style.left = cont.offsetLeft + distX + "px";
}
// check right bounds
if (contBounds.right >= guyBounds.right){
cont.style.left = cont.offsetLeft + distX + "px";
}
// ********************************************************************
lastX = event.pageX;
lastY = event.pageY;
}
}
#container {
height:300px;
width:300px;
outline: 1px solid black;
position:absolute;
left:50px;
top: 0px;
background-color:#CCC;
}
#guy {
position:absolute;
height:50px;
width:50px;
outline: 1px solid black;
background-color:#000;
left: 200px;
top: 200px;
}
<div id="container"></div>
<div id="guy"></div>
try this link to get you started as far as keeping the "guy" inside the "contatiner": http://www.w3schools.com/html/html5_draganddrop.asp
their example shows how you can make an element only drop inside another element.
as far as moving the container...i would think that you could add some if else statements into the moved function that will test the position of the guy against the conatiner's outline and say that when they meet to move the container as well.
i am very new to javascript myself but this is just a suggestion from what i think i understand of it.

How do I position a div relative to the mouse pointer exactly when scroll page?

I found this example on my search.
But it is useless, because when the webpage has long height, and my <div> block isn't on the top, when I scroll the page, there are different distances with different PageY or clientY, so the movable <div> can not exactly go after the mouse cursor.
Here's what I've tried so far:
jQuery("#requestStatusChart").mouseover(function (event) {
var maskVal = '<span id="floatTip" style="position:absolute"><span id="hintdivlogistics" class="RMAHintdivlogistics">' +
+'</span><div class="clear"></div></span>';
jQuery(this).find(".DashboardMask").append(maskVal)
ShowHintInfoLogistics("abc");
//when onmouse out ,remove the elements I appended before.
jQuery(this).find(".DashboardMask").mouseout(function () {
if (typeof jQuery("#hintdivlogistics") != undefined) {
jQuery("#floatTip").fadeOut("slow").remove();
}
});
//move current row
jQuery(this).find(".DashboardMask").mousemove(function (event) {
_xx = event.clientX;
_yy = event.clientY;
_yyPage = event.pageY;
var pos = jQuery(this).position();
console.log((pos.left + " " + pos.top));
jQuery("#floatTip").css({ "top": _yy + "px", "left": _xx - 180 + "px",
"border": "2px solid red"
}).fadeIn("slow");
console.log("x:" + _xx + ",y:" + _yy / _yyPage * _yy);
return false;
});
return false;
});
I don't know of any way to do that reliably, given that you don't know the position of the mouse without a mouse event. You could keep track of the mouse position on mousemove, but as this snippet demonstrates it's far from ideal.
function mousemoved(event) {
var f = document.querySelector('#floater');
console.log(event);
f.style.top = event.pageY + f.scrollTop + 'px';
f.style.left = event.pageX + 'px';
}
document.querySelector('#container').addEventListener('mousemove', mousemoved);
#container {
overflow: scroll;
position: relative;
}
#content {
height: 4000px;
background: lightblue;
}
#floater {
position: absolute;
border: 1px solid black;
padding: 1em 2em;
}
<div id="container">
<div id="floater">Hi</div>
<div id="content">content just to make the container taller</div>
</div>
I have solved this problem use another way.
in X axis we can do like this.
content means your main program width,codes adapted all resolution.
var widthContent = jQuery("#content").width();
jQuery("#floatTip").css("left", _xx - (window.screen.width - widthContent)/2 + "px");

Categories