This is the onclick listener inside an a tag
onclick="showMap('change-img-box',event); return false;"
This is the jquery
function showMap(id,e){
var hpos = e.pageX, ypos = e.pageY; alert(hpos+'----'+ypos);
if($("#"+id).is(":visible")){
$("#"+id).hide();
}else{
$("#"+id).css({"top": ypos+10, "left": hpos+10}).hide().fadeIn(300);
}
}
Not sure why, but IE 7 says that both hpos and ypos are undefined. How can I fix this. Thanks in advance.
Older versions of IE use clientX and clientY instead. Here's the function I use for cross-browser compatibility:
window.getMouseCoords = function(e) {
if( !e) return {x:0,y:0};
if( e.pageX || e.pageY) {
return {x:e.pageX,y:e.pageY};
}
if( e.clientX || e.clientY) {
return {
x:e.clientX+document.body.scrollLeft+document.documentElement.scrollLeft,
y:e.clientY+document.body.scrollTop+document.documentElement.scrollTop
};
}
return {x:0,y:0};
};
Since you're using jquery already, you can initialize the click event using jquery instead of the inline onclick. jQuery normalizes the event object according to W3C standards (http://api.jquery.com/category/events/event-object/)
$('#thing-you-are-clicking').click( function(e) {
var hpos = e.pageX, ypos = e.pageY;
// Do your stuff here...
});
if you need that 'id' data, you can put it into the dom of your button using a data-* property, e.g.
Hi
then you can access the data using .data('id')
$('#thing-you-are-clicking').click( function(e) {
var hpos = e.pageX, ypos = e.pageY;
var id = $(this).data('id');
// Do your stuff here...
});
Related
I have an object with the name "element". If somebody touches the tablet, I would like to return the x and y coordinates of the touch position relative to the object, i. e. the upper left corner of the object has the coordinates x=0 and y=0.
I know how to implement this on desktops:
$(function() {
$(document).mousedown(function(e) {
var offset = $("#element").offset();
var relativeX = (e.pageX - offset.left);
var relativeY = (e.pageY - offset.top);
alert(relativeX+':'+relativeY);
$(".position").val("afaf");
});
});
So the word "mousedown" should be replaced by "touchstart", I guess. However, it still doesn't work.
How do I change the above code such that it works on tablets with "touchstart" instead of "mousedown"?
UPDATE: See Daniel Lavedonio de Lima's answer below
You have to explicitly pull a touches object out of the event, it doesn't contain the coordinates directly. Look at line two of the code below.
Here is the code I always use to get touch/pointer coordinates:
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
x = touch.pageX;
y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
x = e.clientX;
y = e.clientY;
}
Put this inside an event listener that listens for any or all of those events and add your offset calculation and this should work.
Christopher Reid's answer almost worked for me, but I had to make a few ajustments because originalEvent property was not part of the event when I was testing in Google Chrome version 81.0.4044.138 and Mozila Firefox version 76.0.1.
Since I found some answers that use directly the event and other that uses event.originalEvent property, I added a check to use the first if the latter is undefined.
So instead of:
var touch = e.originalEvent.touches[0] || e.originalEvent.changedTouches[0];
I used:
var evt = (typeof e.originalEvent === 'undefined') ? e : e.originalEvent;
var touch = evt.touches[0] || evt.changedTouches[0];
So the full answer then becomes:
if(e.type == 'touchstart' || e.type == 'touchmove' || e.type == 'touchend' || e.type == 'touchcancel'){
var evt = (typeof e.originalEvent === 'undefined') ? e : e.originalEvent;
var touch = evt.touches[0] || evt.changedTouches[0];
x = touch.pageX;
y = touch.pageY;
} else if (e.type == 'mousedown' || e.type == 'mouseup' || e.type == 'mousemove' || e.type == 'mouseover'|| e.type=='mouseout' || e.type=='mouseenter' || e.type=='mouseleave') {
x = e.clientX;
y = e.clientY;
}
Normally you would use e.g. e.touches[0].clientX to handle touch events
A non jquery solution, Assuming you have the following HTML
<div id="touchme" style="width: 200px; height: 200px; background: blue;">
And script
document.getElementById("touchme").addEventListener("touchstart",
function clicked(e) {
var br = document.getElementById("touchme").getBoundingClientRect();
// x & y are relative to the clicked element
var x = e.touches[0].clientX - br.left;
var y = e.touches[0].clientY - br.top;
console.log("x: " + x + " y: " + y);
});
Note the following script handles only the first (of all the possible) touch input
Try this:
$(function(){
$('body').on('touchstart', function(e) {
var offset = $("#element").offset();
var t = e.targetTouches.length > 0 ? e.targetTouches.item(0) : e.touches.item(0);
var relativeX = t.pageX - offset.left;
var relativeY = t.pageY - offset.top;
console.log(relativeX+':'+relativeY);
$(".position").val("afaf");
});
});
PointerEvent supports mouse and touch both.
For example, let's see Sortable.js.
Bind events #L423
el.addEventListener('pointerdown', handler);
Get coords #L574
let touch = (evt.touches && evt.touches[0]) || (evt.pointerType && evt.pointerType === 'touch' && evt);
let clientX = (touch || evt).clientX;
let clientY = (touch || evt).clientY;
I adapted the Domenico solution to move the camera on pc and mobile for threeJS without orbitcontrols:
window.addEventListener("touchmove", function clicked(e) {
cursor.x = e.touches[0].clientX / sizes.width - 0.5
cursor.y = -(e.touches[0].clientY / sizes.height - 0.5)});
In case you have some built-in scroll, you should do it as follows:
const rect = event.target.getBoundingClientRect();
x = event.targetTouches[0].pageX - (rect.left + document.documentElement.scrollLeft);
y = event.targetTouches[0].pageY - (rect.top + document.documentElement.scrollTop);
So, I've made simple function to get the mouse location on a page. I want to make it simpler so I can just pass a variable to another function. Right now, I have this:
$(document).on('mousemove', world, function(e){
var loc = function(){
this.x = function(){
return e.pageX - $(world).offset().left;
}
this.y = function(){
return (e.pageY - $(world).offset().top)*(-1);
}
}
console.log(loc.x, loc.y)
});
The console.log just returns undefined. Is there a way to do this globally so I can use a variable such as loc.x to pass into a function?
You'll want to create an object to the scope of your application. (Putting it to a global level may cause namespace clashes.)
var loc = {
x: 0,
y: 0
};
Then just keep reassigning the properties of your object in your event, in this case it's when you move the mouse to keep track of where the mouse location is.
$(document).on('mousemove', function (e) {
loc.x = e.pageX;
loc.y = e.pageY;
console.log(loc.x, loc.y);
});
JSFiddle
Not that I'm advocating it, but here's how you would do it in the way you tried:
$(document).on('mousemove', "#world", function(e){
var self = this
var loc = function(){
this.x = function(){
return e.pageX - $(self).offset().left;
}
this.y = function(){
return (e.pageY - $(self).offset().top)*(-1);
}
}
var thing = new loc();
console.log(thing.x(), thing.y())
});
You have to call loc() to get the object. And then you have to call thing.x() and thing.y() to execute those functions and get the values.
DEMO
I have an image on my page, and I would like to listen to onmousemove events when the mouse is down. But I can't because in my browser (Firefox), when I drag an image, well actually I drag the image, which I don't want.
Here's my code:
JavaScript part:
document.onmousemove=getMouseCoordinates;
var x;
var y;
var clicked = false;
function getMouseCoordinates(event){
ev = event || window.event;
x = ev.pageX;
y = ev.pageY;
}
function onClickMap(){
var obj = document.getElementById("selectArea");
var tempX = x;
var tempY = y;
obj.style.left = tempX + "px";
obj.style.top = tempY + "px";
clicked = true;
}
function onMoveMap(){
if(clicked){
var obj = document.getElementById("selectArea");
var xToSize = Math.abs(parseInt(obj.style.left) - x);
var yToSize = Math.abs(parseInt(obj.style.top) - y);
obj.style.width = xToSize + "px";
obj.style.height = yToSize + "px";
}
}
HTML part:
<img src="pixels.png" id ="pixelDiv" usemap="#pixelMap" onClick="onClickMap()" onmousemove="onMoveMap()">
Here is a jQuery solution.
This will disable all drags:
$(document).bind("dragstart", function() {
return false;
});
If you want to disable drags only on img elements:
$(document).bind("dragstart", function(e) {
if (e.target.nodeName.toUpperCase() == "IMG") {
return false;
}
});
You can add a mousedown handler that just returns false. This seems to stop the dragging in FF.
ok it's nice, but I suppose it is something firefox specific, now I disabled the onlcick and onmove methods of my image, but I can stil drag the image
now I've found the solution, I was looking for this
http://www.develobert.info/2008/10/disable-firefox-image-drag.html
I'm trying to get a page to have cross browser support, however I keep getting stuck on Mozilla Firefox. I have IE and Chrome working though. The code is:
function positiontip(e){
var e = window.event ? event : e;
if (enabletip) {
var curX;
var curY;
if (e.pageX || e.pageY) {
curX = e.pageX;
curY = e.pageY;
} else if (e.clientX || e.clientY) {
curX = e.clientX + document.body.scrollLeft
+ document.documentElement.scrollLeft;
curY = e.clientY + document.body.scrollTop
+ document.documentElement.scrollTop;
}
When ever I try to use the code, Firefox console spits out an error that
e is undefined "if (e.pageX || e.pageY) {"
I have tried calling the function via
positiontip();
and
positiontip(event);
But neither are working.
any ideas?
Try replacing var e = window.event ? event : e; with e = e || window.event;
Nevermind. The problem was that the function positiontip() was called in another function and the other function was being passed the event. I had to changed the html to pass the event to showtooltip() [the upper function] that then passed the event to positiontip().
IE6 is getting to be pain but it still makes up (apparently) a good chunk of the browser market share, so I need to make this work.
function getPosition(e)
{
e = e || window.event;
var cursor = {x:0, y:0};
if (e.pageX || e.pageY)
{
cursor.x = e.pageX;
cursor.y = e.pageY;
}
else
{
var dex = document.documentElement;
var b = document.body;
cursor.x = e.clientX + (dex.scrollLeft || b.scrollLeft) - (dex.clientLeft || 0);
cursor.y = e.clientY + (dex.scrollTop || b.scrollTop) - (dex.clientTop || 0);
}
return cursor;
}
function outCursor(e){
var curPos = getPosition(e);
alert(curPos);
}
window.captureEvents(Event.MOUSEMOVE);
window.onmousemove = outCursor;
IE is complaining about the Event in window.captureEvents(Event.MOUSEMOVE);
'Event' is undefined.
I think ie6 doesn't supports captureEvents. So try
if (window.captureEvents) {
window.captureEvents(Event.MOUSEMOVE);
}
Try running the script without window.captureEvents(Event.MOUSEMOVE);. I don't think it is necessary. Also, like someone mentioned change the window.onmousemove to document.onmousemove
Also here is a good resource on writing this kind of script http://www.quirksmode.org/js/events_properties.html#position