Why cant i call a function onmousemove? - javascript

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;

Related

XY coords following cursor movements

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.

Javascript addEventListener does it matter what the name of the function is in the second parameter?

Does it matter what the name of the function is in the second parameter of the addEventListern(Parm1, Parm2, Parm3)
I think that the error might have been because not all of the calls were renamed to that specific function name. There are a couple of times when that function is called and I think that would be what probably is causing the errors.
My code works with the below code. You can drag the circle around the canvas.
theCanvas.addEventListener("mousedown", mouseDownListener, false);
But if I change the code to the following.
theCanvas.addEventListener("mousedown", er, false);
And also rename the mouseDownListener method to er I can drag the circle around but when I release the mouse the circle keeps following the mouse pointer around. This seems like an odd behavior and I am not certain as to why this would be.
Question: Does the second parameter function name have to be mouseDownListener exactly or can this be an ad hoc name?
HTML Code:
<!doctype html>
<html lang="en">
<head>
<style type="text/css">
h4 {font-family: sans-serif;}
p {font-family: sans-serif;}
a {font-family: sans-serif; color:#d15423; text-decoration:none;}
</style>
<title>HTML5 Canvas Example - Simple Dragging Objects</title>
<script type="text/javascript">
window.addEventListener("load", canvasApp, false);
var Debugger = function() { };
Debugger.log = function(message) {
try {
console.log(message);
}
catch (exception) {
return;
}
}
function canvasApp() {
var theCanvas = document.getElementById("canvasOne");
var context = theCanvas.getContext("2d");
init();
var numShapes;
var shapes;
var dragIndex;
var dragging;
var mouseX;
var mouseY;
var dragHoldX;
var dragHoldY;
function init() {
numShapes = 1;
shapes = [];
makeShapes();
drawScreen();
theCanvas.addEventListener("mousedown", mouseDownListener, false);
}
function makeShapes() {
var i;
var tempX;
var tempY;
var tempRad;
var tempR;
var tempG;
var tempB;
var tempColor;
for (i=0; i < numShapes; i++) {
tempRad = 10 + Math.floor(Math.random()*25);
tempX = Math.random()*(theCanvas.width - tempRad);
tempY = Math.random()*(theCanvas.height - tempRad);
tempR = Math.floor(Math.random()*255);
tempG = Math.floor(Math.random()*255);
tempB = Math.floor(Math.random()*255);
tempColor = "rgb(" + tempR + "," + tempG + "," + tempB +")";
tempShape = {x:tempX, y:tempY, rad:tempRad, color:tempColor};
shapes.push(tempShape);
}
}
//main function for when the mouse button is clicked -- Once everything is loaded everything depends on this function
function mouseDownListener(evt) {
var i;
var highestIndex = -1;
var bRect = theCanvas.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(theCanvas.width/bRect.width);
mouseY = (evt.clientY - bRect.top)*(theCanvas.height/bRect.height);
//find which shape was clicked
for (i=0; i < numShapes; i++) {
if (hitTest(shapes[i], mouseX, mouseY)) {
dragging = true;
if (i > highestIndex) {
dragHoldX = mouseX - shapes[i].x;
dragHoldY = mouseY - shapes[i].y;
highestIndex = i;
dragIndex = i;
}
}
}
if (dragging) {
window.addEventListener("mousemove", mouseMoveListener, false);
}
theCanvas.removeEventListener("mousedown", mouseDownListener, false);
window.addEventListener("mouseup", mouseUpListener, false);
if (evt.preventDefault) {
evt.preventDefault();
} //standard
else if (evt.returnValue) {
evt.returnValue = false;
} //older IE
return false;
}
function mouseUpListener(evt) {
theCanvas.addEventListener("mousedown", mouseDownListener, false);
window.removeEventListener("mouseup", mouseUpListener, false);
if (dragging) {
dragging = false;
window.removeEventListener("mousemove", mouseMoveListener, false);
}
}
function mouseMoveListener(evt) {
var posX;
var posY;
var shapeRad = shapes[dragIndex].rad;
var minX = shapeRad;
var maxX = theCanvas.width - shapeRad;
var minY = shapeRad;
var maxY = theCanvas.height - shapeRad;
var bRect = theCanvas.getBoundingClientRect();
mouseX = (evt.clientX - bRect.left)*(theCanvas.width/bRect.width);
mouseY = (evt.clientY - bRect.top)*(theCanvas.height/bRect.height);
posX = mouseX - dragHoldX;
posX = (posX < minX) ? minX : ((posX > maxX) ? maxX : posX);
posY = mouseY - dragHoldY;
posY = (posY < minY) ? minY : ((posY > maxY) ? maxY : posY);
shapes[dragIndex].x = posX;
shapes[dragIndex].y = posY;
drawScreen();
}
function hitTest(shape,mx,my) {
var dx;
var dy;
dx = mx - shape.x;
dy = my - shape.y;
return (dx*dx + dy*dy < shape.rad*shape.rad);
}
function drawShapes() {
var i;
for (i=0; i < numShapes; i++) {
context.fillStyle = shapes[i].color;
context.beginPath();
context.arc(shapes[i].x, shapes[i].y, shapes[i].rad, 0, 2*Math.PI, false);
context.closePath();
context.fill();
}
}
function erraseCanvas() {
context.clearRect(0,0,theCanvas.width,theCanvas.height);
}
function clearTheScreenWithRectangle() {
context.fillStyle = "#000000";
context.fillRect(0,0,theCanvas.width,theCanvas.height);
}
function drawScreen() {
//erraseCanvas();
clearTheScreenWithRectangle();
drawShapes();
}
}
</script>
</head>
<body>
<div style="top: 50px; text-align:center">
<canvas id="canvasOne" width="1000" height="500">
Your browser does not support HTML5 canvas.
</canvas>
</div>
</body>
</html>
The second parameter has to be a reference to the function you want called when the event is triggered.
When passing a function, you may call it any, valid javascript identifier.
The second function can be called anything. The behaviour you describe by renaming the function to er could be caused if you forget to rename every occurrence of the function name (especially where it is disabled etc)
No, ceiling cat does not force you to set your function names to anything. You have freedom to name it whatever you like.
The second parameter is just a reference to the function you defined earlier, you can put any function (even anonymous) there.
The second parameter in in this statement can be any valid javascript name.
window.addEventListener("load", canvasApp, false);
Can be any valid name in Javascript that you want it to me.
window.addEventListener("load", ILoveBaseballANDApplePie, false);
window.addEventListener("load", Pizza, false);
window.addEventListener("load", AnyOtherName, false);
function Pizza() {
//do some code here
}
function ILoveBaseballANDApplePie() {
//do some code here
}
For programming purposes I would add the "load" name to the function name some how just so that 2 years later you will remember that that the function has to do with the load parameter. I would purchase a simple book on Javascript and use Notepad++ to go through some simple examples because even after using Javascript for the past 6 months I still find it somewhat of a beast to contend with on some things. With HTML5 you will be using these events probably a lot so I would learn as much as I possibly could about Javascript events.

Clicakble planets

Im trying to make planets that give an alert message when clicked.
Problem is, onmousedown only works on canvas, as far I tested.
Code for planets:
var planets = [];
for (var b=0;b<3;b++) {
planets.push(planet(0,360,Math.random()*600,Math.random()*600));
}
function planet(I,shiips,xpos,ypos){
I = I||{};
I.ships = shiips;
I.x=xpos;
I.y=ypos;
return I;
}
code for click detection; tests both for planet object and the image
update = function(){
planetImage.onmousedown=function(){alert("works!")};
planets[0].onmousedown=function(){alert("works!")};
}
setInterval(update,100);
Im using canvas to draw the images, if that hhelps.
I found the following code that gives mouse position, but it doesnt work for me:
(function() {
var mousePos;
window.onmousemove = handleMouseMove;
setInterval(getMousePosition, 100); // setInterval repeats every X ms
function handleMouseMove(event) {
event = event || window.event; // IE-ism
mousePos = {
x: event.clientX,
y: event.clientY
};
}
function getMousePosition() {
var pos = mousePos;
if (!pos) {
// We haven't seen any movement yet
}
else {
// Use pos.x and pox.y
}
}
})();
Im trying to keep it simple, I don't really like jquery or anything complicated.
Once again: the problem is onmousedown only works on the canvas object, i.e.
canvas.onmousedown=function(){alert("works!")};
I got it working now with this code:
update = function(){
canvas.onmousedown=function(){
var e = window.event;
var posX = e.clientX;
var posY = e.clientY;
alert("X position: "+ posX + " Y position: " + posY);
};
setInterval(update,100);

replacing cursor with image to be used as target in javascript

I've tried for a couple of weeks to trouble shoot this problem and I've come to a dead end.
as a word of warning I'm very new to coding and I may not be able to understand much.
I'm trying to draw an image at the location of the mouse.
this is my script so far
$(function()
{
var canvas = $('#canvas')[0];
var context = canvas.getContext("2d");
var img = new Image();
img.src = 'cross.png';
function getTopLeft(elm)
{
var x, y = 0;
x = elm.offsetLeft;
y = elm.offsetTop;
elm = elm.offsetParent;
while(elm != null)
{
x = parseInt(x) + parseInt(elm.offsetLeft);
y = parseInt(y) + parseInt(elm.offsetTop);
elm = elm.offsetParent;
}
return {Top:y, Left: x};
}
canvas.style.cursor = "none";
canvas.addEventListener("mousemove", function (ev)
{
var mouseX = ev.pageX - getTopLeft(canvas).Left;
var mouseY = ev.pageX - getTopLeft(canvas).Top;
});
function animate()
{
context.onmousemove = function(evt)
{
context.clearRect(0,0,canvas.width,canvas.height);
context.drawImage(img, Left, Top);
}
}
});
I think the problem lies in defining the x y value of the picture ive tried every variable used in the code but to no avail the script loads without error but doesnt draw the image at the mouse location.
I have just realised also that i need the image to be centred over the mouse position.

Rotate a Roulette Wheel with the Mouse

I'm looking at this example (jsfiddle). It's almost what I need, but I need the user to "grab" the roulette with the mouse, then spin it, like you would do with a real one with your hand.
Like, you click and hold on the wheel, it "sticks" to your mouse, then you move your mouse to left or right, and release the button, and the wheel starts to spin until it stops.
Another question is, even if the user is doing that, can I choose a predetermined order to the wheel stops?
This is the jsFiddle:
$(function(){
var overWheel = false;
var mouseDown = false;
var lastMousePos = 0;
$('.wheel').on('mouseover', function(){
overWheel = true;
}).on('mouseout', function(){
overWheel = false;
});
$(document).on('mousedown', function(e){
if(overWheel){
lastMousePos = e.offsetY;
mouseDown = true;
}
}).on('mouseup', function(){
mouseDown = false;
});
$(document).on('mousemove', function(e){
if(overWheel && mouseDown){
handleWheel(e);
}
});
function handleWheel(e) {
var yPos = e.offsetY;
var direction = 0;
var deg = getRotationDegrees($('.wheel'));
if(yPos < lastMousePos){ // mouse is going up, move against the clock
console.log(yPos);
direction = -2;
} else { //mouse is going down, move with the clock
direction = 2;
}
$('.wheel').css({'-webkit-transform': 'rotate(' + (deg + (direction)) + 'deg)'});
}
function getRotationDegrees(obj){
var matrix = obj.css("-webkit-transform");
if(matrix !== 'none') {
var values = matrix.split('(')[1].split(')')[0].split(',');
var a = values[0];
var b = values[1];
var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
} else { var angle = 0; }
return angle;
}
});​
I've managed to work.
I Used the jQuery Rotate library.
Thanks!

Categories

Resources