Javascript mouse click coordinates - javascript

I'm having problems trying to record the exact coordinates a click was made. The first readMouseMove function is working exactly how it is supposed to. Displaying the mouse coordinates when i scroll around. The second mouseClick function should record the coordinates only when a click is made. At the moment it's the same as the function above but it seems I can only use the clientx/y event once. Would there be a way to record the mouse click without having it be relative to an object somewhere?
<script type='text/javascript'>
function readMouseMove(e) {
var xandy = 'x=' + e.clientX + " " +'y=' + e.clientY;
document.getElementById('divOne').innerHTML = xandy;
};
function mouseClick(e) {
var clickers = 'x=' + e.clientX + " " +'y=' + e.clientY;
document.getElementById('divTwo').innerHTML = clickers;
};
function clearAll() {
document.getElementById('divTwo').innerHTML = " "
};
document.onmousemove = readMouseMove;
document = mouseClick;
</script>

you are assigning a mouseClick to document object here:
document = mouseClick;
Should be:
document.onclick = mouseClick;

Related

onclick function not being called? - no errors

I'm defining a class Session that is created for every new session.
In window.onload, the Session object has a mouse click event listener , on click, it fires the handler and 1. checks if anchor tag was clicked and saves href 2. saves the x and y of mouse click.
The problem: The function user.onclick is not working. Doesn't call the anchorLinkClickHandler(); OR window.addEventListener i.e. the click event handler that saves x and y. NO ERRORS. I think there is a syntactical issue with the below code.. don't know what. Ideas?
As shown (in window.onload):
var user = new UserSession('001');
user.onclick = function(event) {
// check if an anchor tag link is clicked, if so, save the href.
user.aTagHref = anchorLinkClickHandler();
// CLICK event listener - save the x and y of mouse click
window.addEventListener("load", function(event){
document.body.addEventListener("click", handleClick)
});
}
Here is the full code:
function UserSession(campaignId) {
this.campaignId = campaignId;
var aTagHref = aTagHref;
this.greeting = function() {
alert('Hi! I\'m ' + this.name + '.');
};
// get the position of click - Event Listener Function
this.getPosition = function(el) {
  var xPosition = 0;
  var yPosition = 0;
 
  while (el) {
    if (el.nodeName == "BODY") {
      // deal with browser quirks with body/window/document and page scroll
      var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
      var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
 
      xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
      yPosition += (el.offsetTop - yScrollPos + el.clientTop);
    } else {
      xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
      yPosition += (el.offsetTop - el.scrollTop + el.clientTop)
    }
 
    el = el.offsetParent;
  }
  return {
    x: xPosition,
    y: yPosition,
a: "hahah",
  };
};
// On click handler
this.handleClick = function(event) {
// Return the current element clicked on
var el = event.currentTarget;
// Return the offset values of the element clicked on
var relOffsetValues = getPosition(el);
// Find the true value of x and y by adding the offset and the to clicked value of x and y
var realValueX = (relOffsetValues.x + event.clientX );
var realValueY = (relOffsetValues.y + event.clientY);
// display the x and y of the mouse click
alert("Clicks x:" + realValueX + ", y:" + realValueY);
// alert("clientx:" + event.clientX + ", real valie:" + realValueX);
}
// On click ANCHOR TAGS SAVE THEM
// Anchor Tags - Capture the href of the link clicked
this.anchorLinkClickHandler = function() {
var aTags = document.getElementsByTagName('a');
for (var i = aTags.length - 1; i >= 0; --i) {
aTags[i].onclick = function() {
aTagHref[i] = this.getAttribute("href");
alert(aTagHref);
};
}
}
// END OF CLASS
}
Window.onload function (where everything is called)
window.onload = function() {
var user = new UserSession('001');
user.onclick = function(event) {
// check if an anchor tag link is clicked, if so, save the href.
user.aTagHref = anchorLinkClickHandler();
// CLICK event listener - save the x and y of mouse click
window.addEventListener("load", function(event){
document.body.addEventListener("click", handleClick)
});
}
// SCROLL Event Listener
// Get the x and y of the scroll
window.addEventListener("scroll", function(event) {
// document.getScroll= function(){
var sx, sy;
if(window.pageYOffset!= undefined){
sx = pageXOffset;
sy = pageYOffset;
console.log(sx +" if " + sy);
// return [pageXOffset, pageYOffset];
}
else{
var d= document, r= d.documentElement, b= d.body;
sx= r.scrollLeft || b.scrollLeft || 0;
sy= r.scrollTop || b.scrollTop || 0;
console.log(sx +" else " + sy);
// return [sx, sy];
}
// }
});
};
Take a look at https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick to better understand.
The click event is raised when the user clicks on an element. The click event will occur after the mousedown and mouseup events.
You will have to create a HTML element first and when that element is clicked you have to execute a function that does all the actions you want.
HTML:
<button id="btn">Click me</button>
JavaScript:
document.querySelector("#btn").onclick = function(event) {
// do things here
}

Window scroll function lag

I have a function that positions a div depending on the webpages position.
function calcNav(){
var b = $('#breadcrumb').offset().top;
var w = $(window).scrollTop();
var x = b - w;
//console.log('breadcrumb from top = ' + b + ' window scrolled = ' + w + ' position of nav = ' + x);
$('.sub-nav').css('top', x);
}
calcNav();
$(window).scroll(calcNav);
The function works great, my only issue is that as its constantly rendering my page speed appears a bit laggy - is there any way I can run the function at the end of the scroll instead of during?
I would recommend to you use it with combination with setTimeout and add small amount of milliseconds:
var scrollTimeout;
$(window).scroll(function() {
clearTimeout( scrollTimeout );
scrollTimeout = setTimeout( calcNav, 50 );
});
clearTimeout in this case is used to not trigger previous call if next scroll event was triggered less than 50ms, in case you think your users will scroll slower you can increase this value for example to 100ms etc.

Javascript addEventListener within addEventListener

This could be a silly question, but I'm having a hard time with a sequence of event listeners that shouldn't be running all the time basically. I want to click a button that will allow certain mouse events to be performed on a <canvas> element. On mousedown there is something logged to the console, and as long as the the mouse is down I want another statement logging to the console, and then on mouseup there should be a final statement and the mousemove logging will cease. At current, anytime after the first mousedown, there is mousemove logging, completely ignoring the mUp boolean to stop it. It might be that there's something wrong about nesting Event Listeners, but I wasn't really aware of any problems it might cause...
Here's my code so far, any help would be appreciated:
function mouseMove() {
var mX = canvas_x,
mY = canvas_y;
console.log('move: ' + mX + ',' + mY + ',' + mouseup);
}
btnRect.addEventListener('click', function (event) {
dRect = false;
c.addEventListener('mousedown', function () {
var x = canvas_x,
y = canvas_y;
mouseup = false;
console.log('down: ' + x + ',' + y + ',' + mouseup);
if(mouseup === false) {
c.addEventListener('mousemove', mouseMove);
} else if (mouseup === true) {
c.removeEventListener('mousemove', mouseMove);
} else {
c.removeEventListener('mousemove', mouseMove);
}
});
c.addEventListener('mouseup', function () {
var eX = canvas_x,
eY = canvas_y;
mouseup = true;
console.log('up: ' + eX + ',' + eY + ',' + mouseup);
});
});

Event Identifiers - ClientX and ClientY

I am trying to better understand the usage of the event attribute clientX and clientY.
I need to find the top and left offset of the mouse pointer when it moves over a particular div . The projectImage(x) function is attached to the onmouseover of the div. x is a function argument based on which the URL of a particular image can be determined.
Now. clientX is the left offset of the pointer at the time the mouseover event happens, so what can I enter for event in event.clientX
Th function below does not work (Reported as Not Defined by the JS Console) I think because of a syntax error in the first two lines.
function projectImage(x)
{
// Should the 1st two lines (right hand side) be x.clientY and x.clientX,
// x is a function argument not event relevant to the pointer offset though
var toffset = x.clientY ; // help_me_here.clientY
var loffset = x.clientX ; // Event_Identifier_??.cleintX
var picdiv = document.getElementById("picdiv") ;
picdiv.style.position = "absolute" ;
picdiv.style.left = loffset + "px" ;
picdiv.style.top = toffset + "px" ;
picdiv.innerHTML = "<img src='" + "http://imageServer.com/" + x.split("|")[1] + "' width='30px' />" ;
picdiv.style.visibility = "visible";
}
All you have to do is pass the event object to the function (and maybe refactor the arguments a bit):
<div onmouseover="projectImage(event || window.event, 'Joey', 123);"> Joey </div>
event || window.event is needed because IE is not passing the event object as argument to the event handler and thus has to be retrieved via window.
Also change your function to be able to access the those arguments:
function projectImage(event, name, id) {
var toffset = event.clientY;
var loffset = event.clientX;
var picdiv = document.getElementById("picdiv") ;
picdiv.style.position = "absolute" ;
picdiv.style.left = loffset + "px" ;
picdiv.style.top = toffset + "px" ;
picdiv.innerHTML = "<img src='http://imageServer.com/" + id + "' width='30px' />" ;
picdiv.style.visibility = "visible";
}
Using meaningful variable names helps to understand the code easier.
As #FelixKling mentions you should be passing the event object.
I recommend switching to addEventListener/attachEvent instead of using inline events as well, I set you up an example here.
var x = document.getElementById('x');
var y = document.getElementById('y');
document.getElementById('test').addEventListener('mousemove', function(e){
x.innerHTML = 'X: ' + e.clientX;
y.innerHTML = 'Y: ' + e.clientY;
});​
If you're dead set on inline events, though, you can do it via <div onmouseover="projectImage(event,'Joey|123');"> Joey </div>

Setting mouse coordinates on fireEvent

I'm trying to emulate a mousemove event in a link in IE8, but I'm not sure if it's possible to set the coordinates of the mouse in the event. This is my code so far:
function Handler()
{
var dump = "";
for(var i in event)
{
dump += ("" + i) + " => " + event[i] + "\n";
}
dumper.value = "";
dumper.value = dump;
}
function Init()
{
document.getElementById("link2").attachEvent("onmousemove", function(){Handler();});
}
function Emulate()
{
var evt = document.createEventObject();
evt.x = 10;
evt.y = 10;
document.getElementById("link2").fireEvent("onmousemove", evt);
}
The event is being attached by calling the Init() function onload. When I call Emulate() the coordinates are the actual coordinates of the cursor. Am I doing something wrong or is this just not possible?
OK I just edited my question to reflect my original failing code (the one I posted was messed up). The solution was to set clientX and clientY instead. x and y will automatically get the values assigned to them:
function Emulate()
{
var evt = document.createEventObject();
evt.clientX = 10;
evt.clientY = 10;
document.getElementById("link2").fireEvent("onmousemove", evt);
}

Categories

Resources