Mouse Click coordinates - a true solution ... is there one? - javascript

There are, as of now, 3,898 posts in StackOverflow regarding mouse click coordinates. They all cover everything on how to find the coordinates for the mouse .... in relation to an element.
Has anyone been able to implement a solution where, at any point of your processing, you can recall the coordinates of the very last mouse click?
I have tried everything and every solution for the last 8 hours or so but cannot come accross anything that can recall the last mouse click coordinates.
Apparently, you have to catch it right where you are processing $('...').click(function(e){...});
How about if I sent the processing somewhere and, within that processing (a few nanoseconds later) I want to find out the coordinates of the last mouse click? How can I retrieve it outside an specific function?
EDIT:
Based on sdleihssirhc's suggestion, I was able to implement a solution that is working for me:
On the main page I have created two divs (to avoid dealing with arrays and global variables):
<div id='mouseX' style='display:none; ' ></div>
<div id='mouseY' style='display:none; ' ></div>
On the main page within the script tags:
$('#wrapper').click(function(e) {
var offset = $(this).offset();
$('#mouseX').text(e.clientX - offset.left);
$('#mouseY').text(e.clientY - offset.top);
});
Whenever needed, I can just:
var clickX = $('#mouseX').text();
var clickY = $('#mouseY').text();
Thank you!

You can set up a global array, for keeping track of coordinates (maybe in an object, whatever). Then you can add an event listener to the document, listening for click. Then it's just a matter of logging the position.
Whenever you want to refer to the position during the last click, just refer to the appropriate element of your global array. (If your logging function unshifted instead of pushing, you could always just look at yourArray[0].)

In the $('...').click(function(e){...}); handler, you can set a global variable with the coordinates. For example:
Globally:
var x = -1, // no previous click
y = -1; // no previous click
In the click handler:
x = e.pageX();
y = e.pageY();
Then, you can just reference x and y when you need the coordinates of the last click.

Related

jQuery drag element not updated in the DOM

I have a book type project. I have functions that all users to add annotations to pages, and if necessary drag and drop to make adjustments in their position. The d & d is working successfully. I have a mouseup event bound to the drag div to capture the new location such as left , top etc...
This works fine, later I trigger a function to index all the divs (annotations) present on the page based on class "rect"
$.each('.rect',function(){
addToIndex(this)
})
I store all the div properties in an index so they can be recreated when the user returns to the page. This works fine if the div has not been dragged. All properties are correct and can be recreated on the page later.
However if the div has been dragged the div still retains the original properties not the new dragged-to location.
For some reason the dragged div is not being updated in the DOM.
I can trace the properties for the div after dropping and they are updated
otherwise the div would not be displayed where it was dropped.
How can I force the dropped object to be updated in the DOM using jQuery ?
Do I have to work directly in the DOM in this case instead of jQuery ?
Okay here is more detail
Once the drag object is dropped I capture position and then want to add this as data to the element...snippet here
// capturing the literal position of element after dragging
var lx = $(obj).position().left - offPos.left
var uy = $(obj).position().top
var ux = $(obj).position().left - offPos.left + $(obj).width()
var ly = $(obj).position().top + $(obj).height()
var rb = new Array(lx,uy,ux-lx,ly-uy)
var rbstr = rb.join(",")
// before dragging rbstr value is 593,31,135,40
console.log(rbstr) // outputs 948,13,135,40
//updating the element with new data here
$(obj).attr("data-rb",rbstr)
console.log(rbstr) // outputs 948,13,135,40 which is correct
// everything here indicates the element has been updated
But when I try to read all the elements with the same class to store their properties the updated element's properties are not updated but just as they where before the drag and drop.
$.each('.rect',function(){
var allData = $(this).data()
console.log($(this).data())
// is correct for all elements except the dragged element
pageAnnots[thisDoc.currentPage].push(allData)
})
Hope this gives more detail about the problem.Note I can resize the 'rect' and the data gets updated just fine.
Seems to me when the 'rect' is dropped it is a proxy, and updating the data is not happening on the original dragged 'rect'
UPDATE: I found the problem - I was assigning data using
$(this).attr('data-x',n)
but then retrieving the data using
$(this)data()
Apparently if you assign data using 'attr' you have to likewise retrieve it using the same 'attr' method
HTML
<body>
<div id="draggable" class="ui-widget-content">
<p>Drag me around</p>
</div>
<input type="Button" name="" value="nextPage" id="next">
</body>
jQuery
$(function() {
$("#draggable").draggable();
$("#next").on("click",function() {
var top = $("#draggable").css("top");
var bottom = $("#draggable").css("bottom");
var left = $("#draggable").css("left");
var right = $("#draggable").css("right");
//send them to next page
});
});
Hope this was what you wanted. The dragable function adds a style attribute to div, if that was what you meant by update DOM.

This object at .mouseenter() function

I'm having a simple (I hope it's simple) question. I'm using 10 divs (div1, div2...) and I want to calculate the distance between two of them. I've already clicked one, that takes the class (img.home). I have the function to calculate the distance between two objects showdistance(div1, div2), but How can I use it to calculate showdistance($('img.home').parent()[0], $(this) ) where (this) is the div, that my cursor is point at at the moment ( .mouseenter(function() {$(this).text(showdistance)}); )
Thanks in advance,
If needed, I can make a jsfiddle with the whole code, but as I believe it is a rather easy thing, that I don't know and the code is a large piece it's easier this way.
Best regards.
Store your last clicked element in a variable.
Then compare the position when you enter an element.
You can apply top, left, right or bottom, if you like.
var clicked = null;
$("someSelection").click(function() {
clicked = $(this);
});
$("someSelection").mouseenter(function() {
// if-statement to ensure that the event won't fire if you haven't clicked one
if(clicked !== null) {
console.log($(this).position().top - clicked.position().top);
console.log($(this).position().left - clicked.position().left);
}
});

Jquery get specific *instance of the class* that triggered an event

I am working on a game in which JSON data is turned into a bunch of classes that are painted on top of the main map. Each icon is a small 20x20 pixel box. Moving the cursor over each box is then meant to change another div's html to relay the information "hidden" inside of each class's value.
My code goes like this:
$('.City_Palace').mousemove(function(e) {
e.stopPropagation();
var x = Math.floor((e.pageX - this.offsetLeft + $("#scrollWindow").scrollLeft()) / tileSize);
var y = Math.floor((e.pageY - this.offsetTop + $("#scrollWindow").scrollTop())/tileSize);
var text = $('#WorldMapMessage').html();
alert(e.target.className);
$('#WorldMapMessage').html(x +', '+ y + " " + $(this).val());
// alert($(this).val());
});
This code currently brings up an alert box with the classname of what caused the event. However, what I need to know is which precise instance of the .City_Palace class triggered the event so I can display the appropriate text. If I were using ids instead of classes, this would be trivial, but for this I need to use classes and know which one is invoking the event.
Thanks for the help!
You already seem to be doing this.
Inside the function you pass into .mousemove(), you have access to this, which refers to the specific instance of the element that's being hovered on. You can use it to get anything else you might need from that specific instance of the element. For example:
$('.City_Palace').mousemove(function(e) {
// $(this) is the specific instance of .City_Palace that's being hovered on.
alert($(this).attr("class")); // Alert the class name.
});

select / cut / pasteInto when window not visible

I'm working on a script where I take a business card design and use it to generate a sheet of paper that has ten cards on it to match a template to print temporary cards. The tricky part here is the bleeds; they'll overlap down the middle so I need to make clipping masks for each one.
I came up with a system where I made the frames that would become the clipping masks, duplicated and moved the cards where they need to go, and then more or less did the following:
dupCard[i].select();
app.cut();
frameGroupFront[i].select();
app.pasteInto();
This works great. But because it's a little resource-intensive, I tried to hide the working file upon creation and use workingFile.windows.add(); at the end as I've done in the past. But when there's no window, select() doesn't work! I get error 90886 stating that "No document windows are open."
How can I select the items I want so that I can cut and paste it without having a visible window? If not possible, is there an alternate solution to the problem?
EDIT:
I was asked to provide a scripting sample, so here's the most basic sample I can furnish:
var newPage = app.documents.add();
var myRectangle = newPage.rectangles.add({geometricBounds:[1, 1, 5, 5]});
var myRectangle2 = newPage.rectangles.add({geometricBounds:[1, 1, 3, 3]});
myRectangle.select();
app.cut();
myRectangle2.select();
app.pasteInto();
This script works. But, take the first line and do app.documents.add(false) instead, and it doesn't work because no document window is open. In this example, I'd like to be able to get the one rectangle inside the other with no window visible.
Instead of using copy and paste, you can manipulate the rectangle objects themselves like this:
var doc = app.documents.add(); // Add a new doc
var page = doc.pages[0]; // Get the first page
var rect = page.rectangles.add({geometricBounds:[30,30,6,6]}) // Make a new rect
var rect2 = rect.rectangles.add({geometricBounds:[20,20,6,6]}); // Add a new rect inside
This can all be done without the window being open since you're manipulating the objects directly. Hope this helps!

Get id of selected element

I'm trying to find a way to get the element id of the currently hovered element to show a popup box / tooltip. At the moment I'm using clientX / clientY to get coordinates but I would really like the popup to be centered over the element I'm hovering.
Is there some way to get this information, for example "who called show_tooltip" or similar to later get the coordinates of the element. Hope this makes sense.
In response to the comment below, this is what I'm currently using.
function show_tooltip(evt) {
var x = evt.clientX -50;
var y = evt.clientY -70;
tooltip.setAttributeNS( null, "transform", "translate(" + x + "," + y + ")" );
tooltip.setAttributeNS( null, "opacity", "0.7" );
}
The problem with this is that the mouse pointer is used for coordinates. While I can use getElementById() to get an element, I do not know which element that called the function.
I don't know if this is what you're looking for:
<div onmouseover="show_tooltip(this)"/>
And you will get the element that fired the event in the js function.
Maybe you could have a look at http://docs.jquery.com/Plugins/Tooltip (demo). Thoose kinds of plugins have already been developed a lot of times. This one is just an example.
Event.target (in your script evt.target) holds the target of the event (an element typically).

Categories

Resources