Setting mouse coordinates on fireEvent - javascript

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);
}

Related

Adding and Removing Event Listeners that Point to Function Declarations inside Constructor Function Expression

I have a problem figuring out how to organize these sets of expressions in a way that works. My constructor is a component of a game editor. Inside of this constructor I have a method that handles when the player clicks on an SVG on the document calling the moveObject expression. The move object correctly moves the object and it seems like inner onMouseMove function declaration is working as intended, but I cannot figure out how to remove these listeners.
I tried bind(this) on the removes too, but those didn't work. Before I try to mess with the function expressions and declarations I wanted to see if any of you had any thoughts on how I could write this code more efficiently. I feel like it is a little clunky right now.
function Editor(game){
this.active = null;
this.moveObject = function(event) {
var x = event.clientX;
var y = event.clientY;
let element = document.elementFromPoint(x, y);
if (element.classList.contains('editorMoveable')) {
do {
element = element.parentElement;
if (element.classList.contains('gameObject'))
break;
} while(element.tagName != "body");
}
this.activeElement = element;
var key = splitElementID(this.activeElement.id);
this.active = this.game.objects[key.object][key.subObject];
let shiftX = event.clientX - this.activeElement.getBoundingClientRect().left;
let shiftY = event.clientY - this.activeElement.getBoundingClientRect().top;
var globalTransform = this.game.calculateGlobals(this.active);
var newPos = moveAt(event.pageX, event.pageY);
this.active.Transform.position.x = newPos.newPosX;
this.active.Transform.position.y = newPos.newPosY;
this.activeElement.style.transform = 'translate(' + newPos.newPosX + 'rem, ' + newPos.newPosY + 'rem)';
function moveAt(pageX, pageY) {
var newPosX = ((pageX - shiftX)/remSize - globalTransform.position.x);
var newPosY = ((pageY - shiftY)/remSize - globalTransform.position.y);
var newRotX = (0);
var newRotY = (0);
var newSclX = (1);
var newSclY = (1);
return {"newPosX": newPosX, "newPosY": newPosY}
}
function onMouseMove(event) {
var newPos = moveAt(event.pageX, event.pageY);
this.active.Transform.position.x = newPos.newPosX;
this.active.Transform.position.y = newPos.newPosY;
this.activeElement.style.transform = 'translate(' + newPos.newPosX + 'rem, ' + newPos.newPosY + 'rem)';
}
function onMouseUp() {
document.removeEventListener('mousemove', onMouseMove);
document.removeEventListener('mouseup', onMouseUp);
this.activeElement = null;
this.active = null;
}
// Move the elem on mousemove
document.addEventListener('mousemove', onMouseMove.bind(this));
document.addEventListener('mouseup', onMouseUp.bind(this));
};
};
Results are as explained in the upper problem. Since the event is not being removed (they stack on each click) I get "cannot read property of null".
Thanks for all the help in advance!
The problem is that onMouseMove is not the same function as onMouseMove.bind(this).
What you can do is assign that to a variable, and then use that variable in both the addEventListener and removeEventListener calls.
let thisOnMouseMove = onMouseMove.bind(this);
let thisOnMouseUp = onMouseUp.bind(this);
function onMouseMove(event) {
var newPos = moveAt(event.pageX, event.pageY);
this.active.Transform.position.x = newPos.newPosX;
this.active.Transform.position.y = newPos.newPosY;
this.activeElement.style.transform = 'translate(' + newPos.newPosX + 'rem, ' + newPos.newPosY + 'rem)';
}
function onMouseUp() {
document.removeEventListener('mousemove', thisOnMouseMove);
document.removeEventListener('mouseup', thisOnMouseUp);
this.activeElement = null;
this.active = null;
}
// Move the elem on mousemove
document.addEventListener('mousemove', thisOnMouseMove);
document.addEventListener('mouseup', thisOnMouseUp);

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
}

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>

Javascript drag and drop code works on div but doesn't work on img

I'm fairly new to JavaScript, so any help would be awesome!
I created this small block of code that let's me grab a div and drag it around. I assign the "dragme" id to the div and all is fine and dandy. The problem is that if I replace that div from my html and put an img element instead (obviously assigning the "dragme" id to the img), things don't work as expected.
When I click to drag the img, it actually moves for about 3 or 4 pixels then it freezes until I lift the mouse button (mouseup).
Is there some property or characteristic that would prevent the img element from acting the same way as the div does?
var isClicked = false;
var startClientX = 0;
var startClientY = 0;
var startLeft = 0;
var startTop = 0;
window.addEventListener("load", addListeners, true);
function addListeners()
{
document.getElementById("dragme").addEventListener("mousedown", mouseIsDown, false);
document.getElementById("dragme").addEventListener("mouseup", mouseIsUp, false);
window.addEventListener("mousemove", moveImage, false);
function mouseIsDown(e)
{
if (isClicked == false)
{
isClicked = true;
startClientX = e.clientX;
startClientY = e.clientY;
startLeft = document.getElementById("dragme").offsetLeft;
startTop = document.getElementById("dragme").offsetTop;
}
}
function mouseIsUp()
{
if (isClicked == true)
{
isClicked = false;
}
}
function moveImage(e)
{
if (isClicked == true)
{
imageLeftDif = e.clientX - startClientX;
imageTopDif = e.clientY - startClientY;
var newLeftPos = (startLeft + imageLeftDif) + "px";
var newTopPos = (startTop + imageTopDif) + "px";
document.getElementById("dragme").style.left = newLeftPos;
document.getElementById("dragme").style.top = newTopPos;
}
}
}
This fixed the problem (answer provided as a comment by syazdani):
I'd venture to say that the built in browser drag and drop for images
is kicking in. Try e.preventDefault and return false in the mousedown
handler. – syazdani Dec 2 '12 at 17:26

Make img not to move in html

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

Categories

Resources