Javascript mouse coordinates - javascript

I am have problems with my HTML5 / Javascript game. On my first menu i have a function "mouseClicked" which gives me exact X and Y coordinates and when i click in an area which i have bordered the game will start... This runs perfectly but when the game finishes and my finish screen pops up i want to click a button but it simply doesnt work. My console is saying that it cannot read the property of "pageX" of undefinied
here is a view from section that keeps bothering me.. I am very new to programming so please be patient with me :P Can i use twice function that scans my coordinates ? :o
function mouseClicked(e) {
mouseX = e.pageX - canvasBg.offsetLeft;
mouseY = e.pageY - canvasBg.offsetTop;
if (Playing == false && over == false) {
if (btnPlay.checkClicked()) { //this works great
playGame();
}
}
if (Playing == false && over == true)
if (btnPlayAgain.checkClicked()) {
init();
}
}
function mouseClicked2(e) {
mouseX = e.pageX - canvasFinish.offsetLeft;
mouseY = e.pageY - canvasFinish.offsetTop;
if (isPlaying == false && over == true)
if (btnPlayAgain.checkClicked()) { // cannot load pageX
init();
}
}

Related

Using if statement to jump to antoher scene in js ProcessingJS library

I'm designing a game where there are two levels.
When a user went through the first level, there will be a button on the screen. I would like to make it possible to jump to scene2 if the user clicks on the button.
Here is the code
var sceneNumber;
var scene2 = function(){
code for scene 2
};
var scene 1 = function () {
code for scene 1
};
scene1();
if (sceneNumber === 1 && mouseX >= 120 && mouseX <= 280 && mouseY >= 230 && mouseY <= 270 & mouseIsPressed) {
scene2();
}
However, when I click on the button, nothing happens
When user clicks on the button, the scene should jump from scene1 to scene2.
I tried mouseClicked function,too. But it didn't work, either.
mouseClicked = function (){
if (sceneNumber === 1 && mouseX >= 120 && mouseX <= 280 && mouseY >= 230 && mouseY <= 270) {
scene2();
}
};

I can't execute functions because of another one

I wanted to change photos in a modal window by swiping my finger in two directions, and this piece of code from the Internet helped:
function swipedetect(el, callback) {
var touchsurface = el,
swipedir,
startX,
startY,
distX,
distY,
threshold = 150, //required min distance traveled to be considered swipe
restraint = 100, // maximum distance allowed at the same time in perpendicular direction
allowedTime = 300, // maximum time allowed to travel that distance
elapsedTime,
startTime,
handleswipe = callback || function (swipedir) {}
touchsurface.addEventListener('touchstart', function (e) {
var touchobj = e.changedTouches[0]
swipedir = 'none'
dist = 0
startX = touchobj.pageX
startY = touchobj.pageY
startTime = new Date().getTime() // record time when finger first makes contact with surface
e.preventDefault()
}, false)
touchsurface.addEventListener('touchmove', function (e) {
e.preventDefault() // prevent scrolling when inside DIV
}, false)
touchsurface.addEventListener('touchend', function (e) {
var touchobj = e.changedTouches[0]
distX = touchobj.pageX - startX // get horizontal dist traveled by finger while in contact with surface
distY = touchobj.pageY - startY // get vertical dist traveled by finger while in contact with surface
elapsedTime = new Date().getTime() - startTime // get time elapsed
if (elapsedTime <= allowedTime) { // first condition for swipe met
if (Math.abs(distX) >= threshold && Math.abs(distY) <= restraint) { // 2nd condition for horizontal swipe met
swipedir = (distX < 0) ? 'left' : 'right' // if dist traveled is negative, it indicates left swipe
} else if (Math.abs(distY) >= threshold && Math.abs(distX) <= restraint) { // 2nd condition for vertical swipe met
swipedir = (distY < 0) ? 'up' : 'down' // if dist traveled is negative, it indicates up swipe
}
}
handleswipe(swipedir)
e.preventDefault()
}, false)
};
But when I wanted to use it this way:
let modall = document.getElementById('modall');
swipedetect(modall, function(swipedir) {
if (swipedir == 'right') plusSlides(-1);
if (swipedir == 'left') plusSlides(1);
});
closeModal() function and others in this modal stopped working. Could somebody say why?
P.S closeModal() and other functions are executed only when I click on some element. Everything was working before I pasted swiping code. Swiping code only works on touch screens, but it doesn't work on a computer, so closeModal() works without problems on a PC.

How to detect mouseleave when mouse button is being held and cursor is out the viewport?

I need to detect when an user move out the mouse outside the view-port (example mouse is on browser address bar) even when the mouse button is being held.
As you can see from the code below, I am able to detect it using mouseout and mouseleave but when keeping the mouse button hold and moving out of the view-port these events are not fired.
Any idea how to solve this issue?
I target FF and Chrome latest version.
http://jsbin.com/gesehoneri/edit?html,output
document.addEventListener('mouseout', function () {
console.log('mouseout');
})
document.addEventListener('mouseleave', function () {
console.log('mouseleave');
})
Try this:
document.addEventListener('mousemove', function(e) {
var top = e.pageY;
var right = document.body.clientWidth - e.pageX;
var bottom = document.body.clientHeight - e.pageY;
var left = e.pageX;
if (top < 10 || right < 10 || bottom < 10 || left < 10) {
console.log('Mouse is out the viewport!');
}
});
body,
html {
height: 100%;
}
With this code, if you press the button inside the window, hold it and move the mouse outside the window, it logs the text. Does this help you?
function myFunctioName(e){
if(e.pageY < 0 || e.pageY > window.innerHeight) {
console.log("outside window vertical");
};
if(e.pageX < 0 || e.pageX > window.innerWidth) {
console.log("outside window horizontal");
};
}
window.addEventListener("mousemove", myFunctioName);
window.addEventListener("mousedown", myFunctioName);
Updated for use without JQuery and included both directions.

Automatic Scrolling Suddenly Stops

I've written the following script with the simple purpose of scrolling to the right when the user hovers over the right side of the screen and scrolling to the left when the user hovers over the left side of the screen. It works fine except that if you leave the mouse in the same spot for too long, then scrolling will stop before reaching the end. It begins scrolling again if you subsequently move the mouse. I can't understand why this is happening, since the code initiates an infinite timed loop which checks mouse position and scrolls accordingly. Its as if the mouse position stops being reported if the mouse is inactive for too long. Any ideas?
var mouseX = 0;
var scrollX = 0;
var timer;
$(document).ready(function() {
// Record the mouse position if the mouse is moved
$(document).mousemove(function(e) {
mouseX = e.pageX;
});
// Record the scroll position if the page is scrolled
$(document).scroll(function() {
scrollX = $(window).scrollLeft();
});
// Initiate the scrolling loop
scroll();
});
function scroll() {
// If the user is hovering over the right side of the window
if ((mouseX - scrollX) > 0.75*$(window).width()) {
scrollX += 1;
$(window).scrollLeft(scrollX);
}
// If the user is hovering over the left side of the window
if ((mouseX - scrollX) < (0.25*$(window).width())) {
scrollX -= 1;
$(window).scrollLeft(scrollX);
}
// Repeat in 5 ms
timer = window.setTimeout('scroll()', 5);
}
I don't know exactly what's wrong with your code, but why don't you use jQuery's animation?
It's more reliable than writing your own.
//inside $(document).ready():
var which = 0;
$('body').mousemove(function(e) {
var w_width = $(window).innerWidth();
var prc = (e.pageX - $(window).scrollLeft())/w_width;
var next_which = prc < 0.25 ? -1 : (prc > 0.75 ? 1 : 0);
if (next_which == which)
return;
which = next_which;
$('html,body').stop(true);
if (which != 0)
$('html,body').animate({scrollLeft: (which > 0 ? $(document).innerWidth()-w_width : 0)}, 2000);
}).mouseleave(function() {
$('html,body').stop(true);
which = 0;
});
​ ​
See fiddle
jQuery's mousemove() event fails to fire when e.pageX > $(window).width() (or thereabouts). Looks like a jQuery bug to me. That could be impeding your progress!

Detect when mouse leaves via top of page with jquery

This Jquery problem has been bugging me for a while now. I developed a script, with one function detecting when the mouse leaves via the top of the page. Here is the code:
$(document).bind("mouseleave", function(e)
{
console.log(e.pageY);
if (e.pageY <= 1)
{
now = new Date();
for (i=0; i < times.length; i++)
{
if (now.getTime() > times[i][0] && now.getTime() < times[i][1])
{
$.fn.colorbox({iframe:true, width:650, height:600, href: "work.html", open: true});
}
}
}
});
This works perfectly for me in all browsers. For some reason it works randomly in Chrome and seemingly not at all in Firefox for a friend that tested the site. In my browser (firefox 3.5.3), e.pageY is logged in the console box as a number near 0, however in my friends browser (also firefox 3.5.3) the lowest value is around 240. I have no idea why this is happening considering identical browsers. Does anyone have a clue as to how to debug this, or another more reliable method to detect when the mouse goes out of the webpage via the top? I hope this makes sense.
The problem appears if your window scrolls down, add a bunch of <br/>s to your page and scroll down one line and you'll see it.
So instead of looking to see if e.pageY <=1, subtract out the scrollTop:
if (e.pageY - $(window).scrollTop() <= 1)
{
// do something
}
I used another technic, almost works for all browsers. The trick is using $("body") or $(window).
$(window) do not work for IE, but $("body") works partially for FF as the body might not fill the whole window.
Here's the full page code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script><script>
var mouseX = 0;
var mouseY = 0;
var theFrame;
$(function() {
theFrame = $("body"); //$(window) for non-IE
theFrame.mousemove( function(e) {
//horizontal distance from edge
mouseX = Math.min(theFrame.width() - e.pageX, e.pageX);
//vertical distance from top
mouseY = e.pageY;
$("#mx").html(mouseX);
$("#my").html(mouseY);
});
theFrame.mouseout(function() {
if(mouseY<=mouseX)
$("#in_out").html("out-top");
else
$("#in_out").html("out");
});
theFrame.mouseover(function() {
$("#in_out").html("in");
});
});
</script>
</head>
<body>
<span id="in_out"></span>
<br />Hor: <span id="mx"></span>
<br />Ver: <span id="my"></span>
</body>
</html>
$(document).on('mouseleave', leaveFromTop);
function leaveFromTop(e){
if( e.clientY < 0 ) // less than 60px is close enough to the top
alert('y u leave from the top?');
}
This doesn't work well on older IE version, because those versions don't report the mouse position as should, but it's good enough.
Here is a vanilla JS solution if you just want something light weight that doesn't need to work in EI
/**
* Trigger an event when the cursor leaves the top of the window
* #param {*} threshold how close does it need to be to the top
* #param {*} cb callback function to trigger
*/
function onExit (threshold, cb) {
threshold = threshold || 60
var hasExited = false
document.addEventListener('mouseout', function (e) {
if (e.clientY < threshold && e.movementY < 0 && !hasExited) {
hasExited = true
cb(e)
}
})
}
Example Usage:
onExit(20, function() {
console.log('Mouse has left the top of the window!')
}
In order to detect mouseleave without taking in account the scroll bar and the autcomplete field or inspect :
document.addEventListener("mouseleave", function(event){
if(event.clientY <= 0 || event.clientX <= 0 || (event.clientX >= window.innerWidth || event.clientY >= window.innerHeight))
{
console.log("I'm out");
}
});
Conditions explanations:
event.clientY <= 0 is when the mouse leave from the top
event.clientX <= 0 is when the mouse leave from the left
event.clientX >= window.innerWidth is when the mouse leave from the right
event.clientY >= window.innerHeight is when the mouse leave from the bottom
Just keep
event.clientY <= 0
If you only want to detect exit on top

Categories

Resources