Using jQuery how to get click coordinates on the target element - javascript

I have the following event handler for my html element
jQuery("#seek-bar").click(function(e){
var x = e.pageX - e.target.offsetLeft;
alert(x);
});
I need to find the position of the mouse on the #seek-bar at the time of clicking. I would have thought the above code should work, but it gives incorrect result

Are you trying to get the position of mouse pointer relative to element ( or ) simply the mouse pointer location
Try this Demo : http://jsfiddle.net/AMsK9/
Edit :
1) event.pageX, event.pageY gives you the mouse position relative document !
Ref : http://api.jquery.com/event.pageX/
http://api.jquery.com/event.pageY/
2) offset() : It gives the offset position of an element
Ref : http://api.jquery.com/offset/
3) position() : It gives you the relative Position of an element i.e.,
consider an element is embedded inside another element
example :
<div id="imParent">
<div id="imchild" />
</div>
Ref : http://api.jquery.com/position/
HTML
<body>
<div id="A" style="left:100px;"> Default <br /> mouse<br/>position </div>
<div id="B" style="left:300px;"> offset() <br /> mouse<br/>position </div>
<div id="C" style="left:500px;"> position() <br /> mouse<br/>position </div>
</body>
JavaScript
$(document).ready(function (e) {
$('#A').click(function (e) { //Default mouse Position
alert(e.pageX + ' , ' + e.pageY);
});
$('#B').click(function (e) { //Offset mouse Position
var posX = $(this).offset().left,
posY = $(this).offset().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
$('#C').click(function (e) { //Relative ( to its parent) mouse position
var posX = $(this).position().left,
posY = $(this).position().top;
alert((e.pageX - posX) + ' , ' + (e.pageY - posY));
});
});

$('#something').click(function (e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
console.log(xPos, yPos);
});

Try this:
jQuery(document).ready(function(){
$("#special").click(function(e){
$('#status2').html(e.pageX +', '+ e.pageY);
});
})
Here you can find more info with DEMO

In percentage :
$('.your-class').click(function (e){
var $this = $(this); // or use $(e.target) in some cases;
var offset = $this.offset();
var width = $this.width();
var height = $this.height();
var posX = offset.left;
var posY = offset.top;
var x = e.pageX-posX;
x = parseInt(x/width*100,10);
x = x<0?0:x;
x = x>100?100:x;
var y = e.pageY-posY;
y = parseInt(y/height*100,10);
y = y<0?0:y;
y = y>100?100:y;
console.log(x+'% '+y+'%');
});

If MouseEvent.offsetX is supported by your browser (all major browsers actually support it), The jQuery Event object will contain this property.
The MouseEvent.offsetX read-only property provides the offset in the X coordinate of the mouse pointer between that event and the padding edge of the target node.
$("#seek-bar").click(function(event) {
var x = event.offsetX
alert(x);
});

see here enter link description here
html
<body>
<p>This is a paragraph.</p>
<div id="myPosition">
</div>
</body>
css
#myPosition{
background-color:red;
height:200px;
width:200px;
}
jquery
$(document).ready(function(){
$("#myPosition").click(function(e){
var elm = $(this);
var xPos = e.pageX - elm.offset().left;
var yPos = e.pageY - elm.offset().top;
alert("X position: " + xPos + ", Y position: " + yPos);
});
});

Related

Javascript mouse click coordinates for image

The assignment says "Your task is to write an HTML file that contains JavaScript that will randomly display one of the images above. If the page is refreshed in the browser, you should get another random image." so I did it.
Now it says "When the user clicks anywhere on the image, display an alert window that shows the X and Y position of where the click occurred relative to the image". Here is my code:
<html>
<head>
<title>Assignment 2</title>
<script type="text/javascript">
var imageURLs = [
"p1.jpg"
, "p2.jpg"
, "p3.jpg"
, "p4.jpg"
];
function getImageTag() {
var img = '<img src=\"';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '\" alt=\"Some alt text\"/>';
return img;
}
</script>
</head>
<body>
<script type="text/javascript">
document.write(getImageTag());
</script>
</body>
</html>
You can actually use HTML for this. The image tag has an attribute known as ismap.
What this attribute does is specify that an image is part of a server-side image map. When clicking on such map, the click coordinates are sent to the server as a url query string.
Images must be nested under links for this to work. Here is an example
<a href="http://www.google.com">
<img src="myimage.png" alt="My Image" ismap">
</a>
If you can't use image maps for this, here is a javascript/jquery solution
First, you need to include the jQuery library at the bottom of your body tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
$(document).ready(function() {
$("img").on("click", function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
alert("X Coordinate: " + x + " Y Coordinate: " + y);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="http://vignette1.wikia.nocookie.net/seraphina/images/b/b2/Dragonseraphina.jpg/revision/latest?cb=20160103194957" height="200" width="200" alt="dragon">
You listen for the click event, and pass in event as the parameter.
The event.pageX property returns the position of the mouse pointer, relative to the left edge of the document.
The map solution will only give you the client side pixel coordinates. If you'd like to get the pixel coordinate relative to the original image you need the naturalHeight and naturalWidth information which has height and width of the original image.
code:
// https://stackoverflow.com/questions/34867066/javascript-mouse-click-coordinates-for-image
document.getElementById(imageid).addEventListener('click', function (event) {
// https://stackoverflow.com/a/288731/1497139
bounds=this.getBoundingClientRect();
var left=bounds.left;
var top=bounds.top;
var x = event.pageX - left;
var y = event.pageY - top;
var cw=this.clientWidth
var ch=this.clientHeight
var iw=this.naturalWidth
var ih=this.naturalHeight
var px=x/cw*iw
var py=y/ch*ih
alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
});
$(document).ready(function() {
$("img").on("click", function(event) {
bounds=this.getBoundingClientRect();
var left=bounds.left;
var top=bounds.top;
var x = event.pageX - left;
var y = event.pageY - top;
var cw=this.clientWidth
var ch=this.clientHeight
var iw=this.naturalWidth
var ih=this.naturalHeight
var px=x/cw*iw
var py=y/ch*ih
alert("click on "+this.tagName+" at pixel ("+px+","+py+") mouse pos ("+x+"," + y+ ") relative to boundingClientRect at ("+left+","+top+") client image size: "+cw+" x "+ch+" natural image size: "+iw+" x "+ih );
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src="https://upload.wikimedia.org/wikipedia/commons/7/77/Avatar_cat.png" height="256" width="256" alt="kitten">
example
click on IMG at pixel (445.5,334.125) mouse pos (148.5,49) relative to boundingClientRect at (483.5,64) client image size: 640 x 480 natural image size: 1920 x 1080
$(document).ready(function () {
$("img").on("click", function (event) {
$('#img_coordinate').html("X Coordinate: " + (event.pageX - this.offsetLeft) + "<br/> Y Coordinate: " + (event.pageY - this.offsetTop));
});
});
html
<img src="img/sample.gif" />
<p id="img_coordinate"></p>
little fork ;)
$(document).ready(function() {
$('img').click(function(e) {
var offset_t = $(this).offset().top - $(window).scrollTop();
var offset_l = $(this).offset().left - $(window).scrollLeft();
w = $(this).prop("width"); // Width (Rendered)
h = $(this).prop("height"); // Height (Rendered)
nw = $(this).prop("naturalWidth") ; // Width (Natural)
nh = $(this).prop("naturalHeight") ; // Height (Natural)
var left = Math.round( (e.clientX - offset_l) );
var top = Math.round( (e.clientY - offset_t) );
x = Math.round((left*nw)/w);
y = Math.round((top*nh)/h);
// $('#img_coordinate').html("Left: " + left + " Top: " + top + "nw: "+nw+" nh: "+nh +"x: "+x+" y: "+y);
$('#img_coordinate').html("click x: "+x+" y: "+y);
});
});

Get click position on the window

I am trying to get the position of the click when the user click whatever part of the window. I found this code in many tutorials but it seems not to work.
(function( $ ) {
$( document ).ready(function() {
$( window ).click(function( e ) {
var offset = $(this).offset(),
relativeX = (e.pageX - offset.left),
relativeY = (e.pageY - offset.top);
alert("X: " + relativeX + " Y: " + relativeY);
});
});
})( jQuery );
Firefox console tells me "TypeError: offset is undefined" and I don't understand why it does not work.
Which is the right way to retrieve the click position on the window?
That code is really close to working. It will work correctly if you replace $(this) with $(e.target). This will get the left and top offsets of the click event, not the window itself.
(function($) {
$(document).ready(function() {
$(window).click(function(e) {
var relativeX = (e.pageX - $(e.target).offset().left),
relativeY = (e.pageY - $(e.target).offset().top);
alert("X: " + relativeX + " Y: " + relativeY);
});
});
})(jQuery);
http://jsfiddle.net/IronFlare/7wsamt87/
If you're clicking on the window like that, you don't really need an offset.
$(window).click(function (e) {
alert("X: " + e.pageX + " Y: " + e.pageY);
});
Your code is assuming the wrong this;
In your listener, this will be window, but $(window).offset(); makes no sense, which is why the method returns null or undefined.
Perhaps you meant to use document.documentElement, document.body or e.target which would be the <html>, <body> or the clicked node, respectively.
$(document.body).offset();
I hope to have find a solution
function showCoords(event) {
var x = event.clientX;
var y = event.clientY;
var coords = "X coords: " + x + ", Y coords: " + y;
document.getElementById("demo").innerHTML = coords;
}
<!DOCTYPE html>
<html>
<body>
<h2 onclick="showCoords(event)">Click this heading to get the x (horizontal) and y (vertical) coordinates of the mouse pointer when it was clicked.</h2>
<p><strong>Tip:</strong> Try to click different places in the heading.</p>
<p id="demo"></p>
</body>
</html>

How to read coordinates of a DIV while it is being dragged ? (Javascript)

I want to read the coordinates of a <div> while it is being dragged and compare it to a static <div> and if at all their positions intersect each other while dragging, it should show some message. I want to accomplish this on web using jquery or javascript. Thanks in advance.
code might be something like this (just a random code)
function onDivDragged(e){
var elemOffset=$("#"+e.target.id).offset();
var elem2Offset=$("#elem2Id").offset();
if(parseInt(elem2Offset.top.replace("px",""))==parseInt(elemOffset.top.replace("px","") && parseInt(elem2Offset.left.replace("px",""))==parseInt(elemOffset.left.replace("px","")))
{
alert("intersection occurred");
}
}
If using jQuery UI is an option then you can use jQuery UI Draggable to achieve this.
Further details are available here http://jqueryui.com/draggable/#events
During drag event get cordinates of div getting dragged and compare it to the static div and compute intersection.
use below javascript code to get the coordinate position of the element
var elemant = document.getElementById('elementID'),
left = element.offsetLeft, // returns X coords
top = element.offsetTop; // returns Y coords
You can use "ondragover" event instead of manually checking coordinates.
http://www.w3schools.com/html/html5_draganddrop.asp
You can get offset of any element using jquery.
var offset = $("#some-element").offset();
// log the values
console.log("top: " + offset.top+ "left: " + offset.left);
try this code.
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="http://jqueryui.com/jquery-wp-content/themes/jquery/css/base.css?v=1">
<style>
#myDiv
{
width: 20px;
height: 20px;
background-color: Red;
}
</style>
<script>
$(document).ready(function () {
$("#myDiv").draggable({
start: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#start").html(" x: " + relX + ", y: " + relY);
},
stop: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#end").html(" x: " + relX + ", y: " + relY);
},
drag: function (e, ui) {
var parentOffset = $(this).parent().offset();
var relX = e.pageX - parentOffset.left;
var relY = e.pageY - parentOffset.top;
$("#current").html(" x: " + relX + ", y: " + relY);
}
});
});
</script>
</head>
<body>
start Position:<span id="start"></span>
<br />
End Position:<span id="end"></span>
<br />
Dragging Position<span id="current"></span>
<div id="myDiv">
</div>
</body>
</html>

Having issues with mousemove and images in Jquery

How can I make the other images also follow the mouse? Not all at the same time, but when I click on the selected image.
How can I calculate the distance where the mouse moved when I click on the image?
See link below.
HTML:
<div id="squarelocation"></div>
<div class="square 1">1</div>
<div class="square 2">2</div>
<div class="square 3">3</div>
Jquery:
$(document).ready(function () {
var i = true;
$(document).on('click', function () {
$(this)[i ? 'on' : 'off']('mousemove', follow);
i = !i;
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$(".2").offset({
left: e.pageX,
top: e.pageY
});
}
});
I suggest you to bind a click event to the square class like this:
var clickedImage;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and assign the context to a variable, so that you can refer to it whenever you needed. And then in your code, refer to that context instead of the hardcoded '.2':
$(clickedImage).offset({
left: e.pageX,
top: e.pageY
});
This way, the image clicked will be referred to, instead of just '2' following the mouse all the time.
Same for calculating the distance between the clicked origin and the current position, you can save the original spot on clicking the image:
var initialX;
var initialY;
$('.square').click(function (e){
initialX = e.pageX;
initialY = e.pageY;
clickedImage = this;
});
and do the calculation in the 'follow' function, of course how the calculation should be is up to you, but here is an example:
var distanceX = xPos - initialX;
var distanceY = yPos - initialY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('#squaredistance').html("Distance from origin: " + distanceX + ", " + distanceY);
Hope this help. jsfiddle: http://jsfiddle.net/FW9jV/1/
You could add an 'active' class for the active square. I added an example.
The active square will always be moving until you click to deactivate it.
http://jsfiddle.net/fG6kr/1/
$(document).ready(function () {
var i = true;
$('.square').on('click', function () {
if( $(this).hasClass("active"))
{
$(this).removeClass("active");
$(document).off('mousemove');
}
else
{
$(this).addClass("active");
$(document).on('mousemove', follow);
}
});
function follow(e) {
var xPos = e.pageX;
var yPos = e.pageY;
$("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
$('.active').offset({
left: e.pageX,
top: e.pageY
});
}
});
demo
$(function() {
$('.square').click(function(){
$(this).toggleClass('sel');
});
$(document).on('mousemove', function(e){
$(".sel").offset({left: e.pageX+10, top: e.pageY+10});
});
});

onMouseMove get mouse position [duplicate]

This question already has answers here:
How to get mouse position in jQuery without mouse-events?
(7 answers)
Closed 3 years ago.
In Javascript, within the Javascript event handler for onMouseMove how do I get the mouse position in x, y coordinates relative to the top of the page?
if you can use jQuery, then this will help:
<div id="divA" style="width:100px;height:100px;clear:both;"></div>
<span></span><span></span>
<script>
$("#divA").mousemove(function(e){
var pageCoords = "( " + e.pageX + ", " + e.pageY + " )";
var clientCoords = "( " + e.clientX + ", " + e.clientY + " )";
$("span:first").text("( e.pageX, e.pageY ) - " + pageCoords);
$("span:last").text("( e.clientX, e.clientY ) - " + clientCoords);
});
</script>
here is pure javascript only example:
var tempX = 0;
var tempY = 0;
function getMouseXY(e) {
if (IE) { // grab the x-y pos.s if browser is IE
tempX = event.clientX + document.body.scrollLeft;
tempY = event.clientY + document.body.scrollTop;
}
else { // grab the x-y pos.s if browser is NS
tempX = e.pageX;
tempY = e.pageY;
}
if (tempX < 0){tempX = 0;}
if (tempY < 0){tempY = 0;}
document.Show.MouseX.value = tempX;//MouseX is textbox
document.Show.MouseY.value = tempY;//MouseY is textbox
return true;
}
This is tried and works in all browsers:
function getMousePos(e) {
return {x:e.clientX,y:e.clientY};
}
Now you can use it in an event like this:
document.onmousemove=function(e) {
var mousecoords = getMousePos(e);
alert(mousecoords.x);alert(mousecoords.y);
};
NOTE: The above function will return the mouse co-ordinates relative to the viewport, which is not affected by scroll. If you want to get co-ordinates including scroll, then use the below function.
function getMousePos(e) {
return {
x: e.clientX + document.body.scrollLeft,
y: e.clientY + document.body.scrollTop
};
}
It might be a bit overkill to use d3.js just for finding mouse coordinates, but they have a very useful function called d3.mouse(*container*). Below is an example of doing what you want to do:
var coordinates = [0,0];
d3.select('html') // Selects the 'html' element
.on('mousemove', function()
{
coordinates = d3.mouse(this); // Gets the mouse coordinates with respect to
// the top of the page (because I selected
// 'html')
});
In the above case, the x-coordinate would be coordinates[0], and the y-coordinate would be coordinates[1]. This is extremely handy, because you can get the mouse coordinates with respect to any container you want to by exchanging 'html' with the tag (e.g. 'body'), class name (e.g. '.class_name'), or id (e.g. '#element_id').
Especially with mousemove events, that fire fast and furious, its good to pare down the handlers before you use them-
var whereAt= (function(){
if(window.pageXOffset!= undefined){
return function(ev){
return [ev.clientX+window.pageXOffset,
ev.clientY+window.pageYOffset];
}
}
else return function(){
var ev= window.event,
d= document.documentElement, b= document.body;
return [ev.clientX+d.scrollLeft+ b.scrollLeft,
ev.clientY+d.scrollTop+ b.scrollTop];
}
})()
document.ondblclick=function(e){alert(whereAt(e))};

Categories