Javascript mouse click coordinates for image - javascript

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

Related

Get correct click position on scaled image

This is how I get the click position when clicking on an image to do some image transformation. But my problem is, that the image has the CSS attribute max-width: 1000px. So the code works only for images which are smaller. For larger images the position result is not the real pixel which was clicked on.
My question is, if it is possible to calculate the correct click position for the natural sized image. An alternative would be to set some data attributes with the real image size like data-width: '1200px' and data-height: '1000px'. But still I have to do some calculation.
parentPosition = getPosition(event.currentTarget),
x = event.clientX - parentPosition.x,
y = event.clientY - parentPosition.y;
function getPosition(element) {
var xPosition = 0;
var yPosition = 0;
while (element) {
xPosition += (element.offsetLeft - element.scrollLeft + element.clientLeft);
yPosition += (element.offsetTop - element.scrollTop + element.clientTop);
element = element.offsetParent;
}
return { x: xPosition, y: yPosition };
}
If you know natural size and current size, i think you can just do this:
naturalClickPosX = (naturalWidth / currentWidth) * currentClickPosX;
naturalClickPosY = (naturalHeight / currentHeight) * currentClickPosY;
Have a look at this JSFiddle
HTML
<img src="http://placehold.it/1200x1000" width="1000">
JavaScript
$('img').on("click", function(e){
var $img = $(this);
var currentClickPosX = e.pageX - $img.offset().left;
var currentClickPosY = e.pageY - $img.offset().top;
var currentWidth = $img.width();
var currentHeight = $img.height();
var naturalWidth = this.naturalWidth;
var naturalHeight = this.naturalHeight;
var naturalClickPosX = ((naturalWidth / currentWidth) * currentClickPosX).toFixed(0);
var naturalClickPosY = ((naturalHeight / currentHeight) * currentClickPosY).toFixed(0);
alert("Current X: " + currentClickPosX + " Current Y: " + currentClickPosY +
"\r\nNatural X: " + naturalClickPosX + " Natural Y: " + naturalClickPosY);
});
try this , will work on all sizes
$('.img-coordinate').click(function(e){
var parentOffset = $(e.target).parent().offset();
// here the X and Y on Click
X = e.pageX - $(e.target).offset().left;
Y = e.pageY - $(e.target).offset().top;
alert(X + ' , ' + Y );
});
working fiddel : https://jsfiddle.net/h09kfsoo/

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>

Create a mark on an image using relative positioning?

I'd like to be able to mark an image where a user clicks, store the coordinates, and then be able to recreate the marks at a later time. I've got the storing part down but I'm having trouble getting the mark image to show up on the image.
I found a similar question here using absolute positioning, but I'd like the coordinates to be relative to the image.
Looks like jQuery position will give me the position relative to the parent, but from there how would I create and position the mark image relative to the parent? Any help would be greatly appreciated. Thanks
<div id="container">
<img id="imgtoclick"></img>
</div>
$(document).ready(function() {
$("#imgtoclick").click(function(e) {
e.preventDefault();
var left = this.position.left;
var top = this.position.top;
//how to create mark image relative to parent
var img = $('<img>');
})
});
Following #Blenders post but in case your images are nested within positioned elements, you will need to get the coordinates recursively:
var myImg = ...
var getAbsoluteOffset = function (el) {
var x=0, y=0;
while (el) {
x += el.offsetLeft;
y += el.offsetTop;
el = el.offsetParent;
};
return {x:x,y:y};
}
myImg.onclick = function(evt) {
var offset, x, y;
offset = getAbsoluteOffset(this);
var x = evt.pageX - offset.x;
var y = evt.pageY - offset.y;
alert('x: ' + x + '\ny: ' + y);
};
This should do what you want:
$('img').click(function(event) {
var x = event.pageX - this.offsetLeft;
var y = event.pageY - this.offsetTop;
alert('X: ' + x + '\nY:' + y);
});
You would follow these steps:
Give #container this style
container
{
position: relative;
}
Give the image that will show the mark this style
mark
{
position: absolute;
left: //left from jQuery
top: //top from jQuery position
}

Using jQuery how to get click coordinates on the target element

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

How to zoom in an image and center it?

Any Idea how to zoom in a image on particular point using javascript, css ? I am using webkit based browser.
I can zoom by specifying zoom property , like `elem.style.zoom="150%",
Main problem is I cannot center the image where I want to zoom.
I can get the point where I want to zoom using mouseclick.
As I said in my comment above, I would avoid the zoom css property and stick to just javascript. I managed to throw together the following code which works pretty well for the first click, really all it needs is a little more dynamically (even a word?).
<html>
<head>
<script type="text/javascript">
function resizeImg (img)
{
var resize = 150; // resize amount in percentage
var origH = 200; // original image height
var origW = 200; // original image width
var mouseX = event.x;
var mouseY = event.y;
var newH = origH * (resize / 100) + "px";
var newW = origW * (resize / 100) + "px";
// Set the new width and height
img.style.height = newH;
img.style.width = newW;
var c = img.parentNode;
// Work out the new center
c.scrollLeft = (mouseX * (resize / 100)) - (newW / 2) / 2;
c.scrollTop = (mouseY * (resize / 100)) - (newH / 2) / 2;
}
</script>
<style type="text/css">
#Container {
position:relative;
width:200px;
height:200px;
overflow:hidden;
}
</style>
</head>
<body>
<div id="Container">
<img alt="Click to zoom" onclick="resizeImg(this)"
src="https://picsum.photos/200" />
</div>
</body>
</html>
It works in Google Chrome and IE, not sure about others. Like I said hopefully it will point you in the right direction.
What has to be done.
Get the location of the click inside the image. This might seem easy but it is not because the pageX and pageY of the event hold the coordinates in regard to the document. To calculate where inside the image someone clicked you need to know the position of the image in the document. But to do this you need to factor in all the parents of it, as well as if they are relative/absolute/static positioned .. it gets messy..
calculate the new center (the click position scaled - the top/left position of the container)
scale the image and scroll the container to the new center
if you do not mind using jQuery for it then use the following (tested)
<script type="text/javascript">
$(document).ready(
function(){
$('#Container img').click(
function( event ){
var scale = 150/100;
var pos = $(this).offset();
var clickX = event.pageX - pos.left;
var clickY = event.pageY - pos.top;
var container = $(this).parent().get(0);
$(this).css({
width: this.width*scale,
height: this.height*scale
});
container.scrollLeft = ($(container).width() / -2 ) + clickX * scale;
container.scrollTop = ($(container).height() / -2 ) + clickY * scale;
}
);
}
);
</script>
and the html needed
<div id="Container">
<img alt="Click to zoom" src="http://sstatic.net/so/img/logo.png" />
</div>
In following code, the image is amplified at the mouse click point - the image is amplified, but the point where you clicked remains under your mouse cursor, and the size of the frame remains the same. Right-click to go back to original display ratio.
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<style>
div {
width: 400px;
height: 600px;
overflow: hidden;
}
img {
position: relative
}
</style>
<script src="http://code.jquery.com/jquery-1.7.2.js"></script>
<script type="text/javascript">
var imageOffset_x = 0;
var imageOffset_y = 0;
function onZoom()
{
var mouseInFrame_x = event.x;
var mouseinFrame_y = event.y;
var mouseInImage_x = imageOffset_x + mouseInFrame_x;
var mouseInImage_y = imageOffset_y + mouseinFrame_y;
imageOffset_x += mouseInImage_x * 0.16;
imageOffset_y += mouseInImage_y * 0.16;
var image = $('#container img');
var imageWidth = image.width();
var imageHeight = image.height();
image.css({
height: imageHeight * 1.2,
width: imageWidth * 1.2,
left: -imageOffset_x,
top: -imageOffset_y
});
}
function onRightClick() {
imageOffset_x = 0;
imageOffset_y = 0;
$('#container img').css({
height: 600,
width: 400,
left: 0,
top: 0
});
return false;
}
</script>
</head>
<body>
<a id="zoom" href="#" onclick="onZoom();">Zoom</a>
<div id="container">
<img src="~/Images/Sampple.jpg" width="400" height="600" onclick="onZoom();" oncontextmenu="onRightClick(); return false;"/>
</div>
</body>
</html>

Categories