XY coords following cursor movements - javascript

i am looking to have this cursor effect on the body:
https://www.screenshot-magazine.com/
i do have two separate codes, one for the bloc following the mouse and another to get the xy coords.
But i am too beginner to merge both together or make both work in parallel to have the XY coods printed in the box following my cursor moves.
Someone could help me?
Thanks a lot in advance:)
Anto
here the two codes:
1-bloc following mouse movements
<style>
#divtoshow {
position:absolute;
display:none;
color: #C0C0C0;
background-color: none;
}
<script type="text/javascript">
var divName = 'divtoshow'; // div that is to follow the mouse (must be position:absolute)
var offX = 15; // X offset from mouse position
var offY = 15; // Y offset from mouse position
function mouseX(evt) {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) {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(evt) {
var obj = document.getElementById(divName).style;
obj.left = (parseInt(mouseX(evt))+offX) + 'px';
obj.top = (parseInt(mouseY(evt))+offY) + 'px';
}
document.onmousemove = follow;
</script>
<body>
<div id='onme' onMouseover='document.getElementById(divName).style.display="block"' onMouseout='document.getElementById(divName).style.display="none"'>
<div id="divtoshow">test</div>
2-get XY coords on body
<script>
function readMouseMove(e){
var result_x = document.getElementById('x_result');
var result_y = document.getElementById('y_result');
result_x.innerHTML = e.clientX;
result_y.innerHTML = e.clientY;
}
document.onmousemove = readMouseMove;
</script>
</head>
<body>
<h2 id="x_result">0</h2>
<h2 id="y_result">0</h3>
</body>

Your CSS is fine. You could have moved #x-result and #y-result into #divtoshow, and then set the left and right in readMouseMove. I've modified your code a bit. I'll explain it on the way
const xResult = document.getElementById("x-result");
const yResult = document.getElementById("y-result");
const divToShow = document.getElementById("divtoshow");
document.onmousemove = function (e) {
let mouse = {
x: e.clientX, // this is 2018, so you can just directly use clientX
y: e.clientY // and clientY
};
divToShow.style.left = `${mouse.x + 16}px`; // add a padding so that the text is not rendered directly below the mouse
divToShow.style.top = `${mouse.y + 16}px`;
xResult.innerHTML = `X: ${mouse.x}`; // write the text into the output divs
yResult.innerHTML = `Y: ${mouse.y}`;
};
#divtoshow {
color: #C0C0C0;
position: absolute;
}
<div id="divtoshow">
<span id="x-result">X: 0</span> <br> // i changed the h2s to spans because h2s have HUGE text
<span id="y-result">Y: 0</span>
</div>
You can add the #onme integration by yourself.

Related

How to click and drag a large view like in google maps?

Suppose I have a large view with scroll in both x and y direction and instead of scrolling with mouse scroll, I need to drag and move to navigate through the entire view like in google maps
<div id="wrapper">
<div id="dragable_content">
<img src="https://geology.com/world/world-map.gif" style="height:100rem;"/>
</div>
</div>
how do I achieve this? preferably using only pure js
Thanks to the solution provided by #grisuu in the comments
I was able to whip up this:
jsfiddle
var _startX = 0;
var _startY = 0;
var _offsetX = 0;
var _offsetY = 0;
var _dragElement;
document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;
function OnMouseDown(event){
document.onmousemove = OnMouseMove;
_startX = event.clientX;
_startY = event.clientY;
_offsetX = document.getElementById('div1').offsetLeft;
_offsetY = document.getElementById('div1').offsetTop;
_dragElement = document.getElementById('div1');
}
function OnMouseMove(event){
_dragElement.style.left = (_offsetX + event.clientX - _startX) + 'px';
_dragElement.style.top = (_offsetY + event.clientY - _startY) + 'px';
}
function OnMouseUp(event){
document.onmousemove = null;
_dragElement=null;
}
html{
background-color:green;
overflow: hidden;
}
.div1{position:absolute; height:500px; width: 500px; z-index:1;}
<div class="div1" id="div1">
<div style="height:50px;width:50px;background-color:red;"></div>
<div style="position:absolute;top:75px;left:100px;height:50px;width:50px;background-color:blue;"></div>
</div>
I implemanted the same feature for my personal project by editing arsher's answer and I want to share the code I ended up with here.
Here are some notes:
This code does not use css at all, it's using scrollTo instead.
I'm using draggable='false' on the image to prevent browser dragging feature on images.
document.documentElement.scrollTop / .scrollLeft could have some browser support issues, there are many ways to get document scroll position value, many of them didn't work for me and this one did
/* check browser support, tested on Chrome v108
**********************************************************************/
let _startX = 0,
_startY = 0,
_scrollTop = 0,
_scrollLeft = 0;
document.onmousedown = OnMouseDown;
document.onmouseup = OnMouseUp;
function OnMouseDown(event) {
document.onmousemove = OnMouseMove;
_startX = event.clientX;
_startY = event.clientY;
_scrollTop = document.documentElement.scrollTop;
_scrollLeft = document.documentElement.scrollLeft;
}
function OnMouseMove(event) {
window.scrollTo({
left: _scrollLeft + (_startX - event.clientX),
top: _scrollTop + (_startY - event.clientY)
});
}
function OnMouseUp() {
document.onmousemove = null;
}
<div id="wrapper">
<div id="dragable_content">
<img draggable='false' src="https://geology.com/world/world-map.gif" style="height:100rem;" />
</div>
</div>

Make div follow cursor on button click, and stop following cursor and go back to starting position on (another) button click

var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');
function mouseMov(e) {
bx.style.left = -50 + e.clientX + "px";
bx.style.top = -50 + e.clientY + "px";
bx.style.zIndex = -99;
}
takeMeBtn.clickToggle = function fn(e) {
bx.style.left = -50 + e.clientX + "px";
bx.style.top = -50 + e.clientY + "px";
bx.style.zIndex = -99;
}
letGoBtn.onclick = function() {
bx.style.position = "fixed";
bx.style.top = 50;
bx.style.left = 50;
}
Hey people!
I've been trying to get "movingbox" to move and follow the cursors positions, when I click the button "takeMeBtn".
But, it only places itself in the current position of the cursor, when the "takeMeBtn" is clicked, and then stays there.
I also want to make it go back to its starting position, or anyposition, when I click "letGoBtn", but I think I can manage that one on my own.
I do not want to use jQuery for this.
Superthankful for any help.
Your buttons need to activate a mousemove listener for whatever you want to track the mouse over, probably the document or window. Other than that, you were close. I used inline style, but obviously a separate css document is better outside of this narrow example.
var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');
function mouseMov(e) {
bx.style.left = -50 + e.clientX + "px";
bx.style.top = -50 + e.clientY + "px";
}
takeMeBtn.onclick = function(e) {
document.addEventListener('mousemove', mouseMov)
}
letGoBtn.onclick = function() {
document.removeEventListener('mousemove', mouseMov)
bx.style.top = "";
bx.style.left = "";
}
<button id="takeMeBtn">click</button>
<button id="letGoBtn">unclick</button>
<div id="movingbox" style="width:30px; height:30px; border: 1px solid black; position:absolute;"></div>
You can do it like this.
HTML:
<button id="takeMeBtn">take me</button>
<button id="letGoBtn">let go</button>
<div id="movingbox"></div>
var bx = document.getElementById("movingbox");
var takeMeBtn = document.getElementById('takeMeBtn');
var letGoBtn = document.getElementById('letGoBtn');
CSS
div {
width: 50px;
height: 50px;
background: red;
position: absolute;
}
JS
// flag: div should/not move
let move = false;
// switch flag
takeMeBtn.addEventListener('click', event => {
move = true;
});
// reset flag and position
letGoBtn.addEventListener('click', event => {
move = false;
bx.style.top = 0;
bx.style.left = 0;
bx.style.zIndex = 0;
});
// change its position on each mousemove event if the flag is set to true
document.addEventListener('mousemove', event => {
if (move === true) {
bx.style.top = event.clientY + 'px';
bx.style.left = event.clientX + 'px';
bx.style.zIndex = -99;
}
});

Why cant i call a function onmousemove?

Here's the simplified code, it should get the coordinates of the mouse when it moves.
The JavaScript:
document.body.onmousemove = move;
function move (e) {
var xyz = document.getElementById("coord");
x = e.clientX ;
y = e.clientY ;
xyz.innerHTML = x +" "+ y ;
}
The HTML:
<div id="coord"></div>
It works well on CodePen but not on a website.
function move(e) {
alert("mouse movement detected!");
}
document.onmousemove = move;

How to move a "div" to certain coordinates using Javascript?

I would like to know , how to position a div block dynamically to the place where mouse clicks.
I know how to get the value of coordinates of click dynamically.
I want to know how we can move the div block to that coordinate.
I tried the following codes in SO, but nothing is working
document.getElementById('someID').style.position='absolute';
document.getElementById('someID').style.left='500px';
document.getElementById('someID').style.top='90px';
and the below code
var d = document.getElementById('yourDivId');
d.style.position = "absolute";
d.style.left = x_pos;
d.style.top = y_pos;
Can anyone tell me how to do it.
Thanks,
You have missed the units in your position assigning sentence.
To get the mouse position (on click):
(function() {
window.onmousedown = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event; // IE-ism
console.log(event.clientX);
moveDiv(event.clientX,event.clientY);
}
})();
Then send the position to a function to change the position of your div, adding the pixels unit, don't forget it!
function moveDiv(x_pos,y_pos){
var d = document.getElementById('myDiv');
d.style.left = x_pos + "px";
d.style.top = y_pos + "px";
}
Full Code:
(function() {
window.onmousedown = handleMouseMove;
function handleMouseMove(event) {
event = event || window.event; // IE-ism
console.log(event.clientX);
moveDiv(event.clientX,event.clientY);
}
})();
function moveDiv(x_pos,y_pos){
var d = document.getElementById('myDiv');
d.style.left = x_pos + "px";
d.style.top = y_pos + "px";
}
DEMO
try
document.body.addEventListener('click', function(e) {console.log(e)})
you got a mouseevent object where its properties clientX, clientY gives the location of mouse click.
You can then use this to re-position your div.
You need to add px after d.style.left and d.style.top.
Try this:
<style>
#someID {
position:absolute;
left: 0px;
top: 0px;
height: 50px;
width: 50px;
background: red;
}
</style>
<div id="someID">
</div>
<script>
var ele = document.getElementById('someID');
document.onclick = function(e) {
ele.style.top = e.offsetY + "px";
ele.style.left = e.offsetX + "px";
}
</script>
Here is an example: http://jsfiddle.net/s99d4/
JS
var a = document.getElementById('a');
document.onclick = function(e){
a.style.top = e.clientY + 'px';
a.style.left = e.clientX + 'px'
}
CSS
div {
position: absolute;
}
JSFiddle
You can use this simple line of Jquery instead of going those complicated routes.
$("#divId").hide();
$('body').click(function(event) {
$("#divId").show().css( {position:"absolute", top:event.pageY, left: event.pageX});
});
First you hide the div you want to move (OR don't hide it)
Then move it wherever the user clicks. See FIDDLE
EDIT: Never mind, not all of them look so complicated anymore... Goodluck. :)
Hope this helps.
Mike
Use
d.style.position = "absolute";
d.style.top = "980px"; //or whatever
d.style.left = "970px"; //or whatever
Remember that d.style.top is the y-axis and d.style.left is the x-axis.
Therefore,
d.style.top = e.clientY + "px";
d.style.left = e.clientX + "px";
Here is a full function for this code:
document.onmousemove = getCoords;
function getCoords(e) {
e = e || window.event;
var x = e.clientX;
var y = e.clientY;
var div = document.getElementById("MYDIV");
div.style.position = "absolute";
div.style.top = y + "px";
div.style.left = x + "px";
}

Trying to move boxes

I have a random amount of boxes, randomly on a page of random colors. I am trying to be able to get them to move from one place to another.
Essentially, I am not familiar at all with mouse move events so this is quite the challenge. Even though it is quite simple.
Heres the code for the HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Ramdom Boxes</title>
<script src="A2Q1.js"></script>
</head>
<body>
</body>
</html>
Javascript:
window.onload = init;
function init() {
//when page is loaded create a bunch of boxes randomly throughout the page
//get the body element of the document
var body = document.getElementsByTagName("body")[0];
//store width and height of boxes
var boxWidth = 50;
var boxHeight = 50;
//create the random number for the boxes
var randNum = Math.floor(Math.random() * 500 + 1);
//create the boxes
for(var i=0;i<randNum;i++){
//create the random color and random positions
var colour = Math.round(0xffffff * Math.random()).toString(16);
var pos1 = Math.floor(Math.random() * window.innerWidth)
var pos2 = Math.floor(Math.random() * window.innerHeight)
// Define an array of css attributes
var attr =[
// Assign a colour to the box
'background-color:#' + colour,
// Place the box somewhere inside the window
'left:' + pos1 + 'px',
'top:' + pos2 + 'px',
// Set the box size
'width:' + boxWidth + 'px',
'height:' + boxHeight + 'px',
'cursor: pointer;',
'position:absolute;'
];
//join the attributes together
var attributes = attr.join(';');
//create a new div tag
var div = document.createElement("div");
//gives the box a unique id
div.setAttribute("id","box"+i)
//create the design of the box
div.setAttribute("style",attributes);
//add to the body
body.appendChild(div);
}
}
I really have no idea where to start...
Well a start would certainly be getting the mouse position, after that the world is your oyster.
var mousex = 0;
var mousey = 0;
function getXY(e){
if (!e) e = window.event;
if (e)
{
if (e.pageX || e.pageY)
{ // this doesn't work on IE6!! (works on FF,Moz,Opera7)
mousex = e.pageX;
mousey = e.pageY;
go = '[e.pageX]';
if (e.clientX || e.clientY) go += ' [e.clientX] '
}
else if (e.clientX || e.clientY)
{ // works on IE6,FF,Moz,Opera7
mousex = e.clientX + document.body.scrollLeft;
mousey = e.clientY + document.body.scrollTop;
go = '[e.clientX]';
if (e.pageX || e.pageY) go += ' [e.pageX] '
}
}
}
With the mouse info you can then do this in another function.
function moveBoxes(){
document.body.onmousemove = updater; //or some container div!
updater();
}
function updater(e){
getXY(e);
document.getElementById('aboxid').style.left=mousex+'px';
}
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>MouseDown MouseUp</title>
<meta charset="UTF-8">
<style>
#insideBox{
height: 100px;
width: 100px;
background-color: black;
left:300px;
top:300px;
position:absolute;
}
</style>
<script>
var mouseFire = null;
window.onload = init;
function init(){
var div = document.getElementById("insideBox");
div.addEventListener("mousedown",mouseDrag,false);
}
function mouseDrag(e){
var evt = e || window.event;
mouseFire = evt.target || evt.srcElement;
document.addEventListener("mousemove",mouseMove,false);
document.addEventListener("mouseup",mouseDrop,false);
}
function mouseMove(e){
var evt = e || window.event;
var mouseX = evt.clientX;
var mouseY = evt.clientY;
mouseFire.style.left = mouseX-50+"px";
mouseFire.style.top = mouseY-50+"px";
}
function mouseDrop(e){
mouseFire = null;
document.removeEventListener("mousemove",mouseMove,false);
}
</script>
</head>
<body>
<div id="insideBox"></div>
</body>
</html>

Categories

Resources