In my php script it is generated using echo javascript, as well as a lot of pictures using the img tag. Each picture has its own ID.

I need in javascript on ID to get the coordinates of the image generated from php. How can I do it?

So my pictures are generated in php:

  foreach($files as $str){ echo '<tr>'; echo "<td><tr><img onclick='javascript:imgclick($ii)' id = '$ii' src='http://clroyale.ru/wp-content/plugins/royale/cards/$str'></img></tr></td>"; echo '</tr>'; $ii = $ii + 1; } 
  • By coordinates, do you mean the path to the picture? If so, why not send it instead of the ID of the picture, once you manipulate it? - VenZell
  • No, the coordinates are the location of the picture on the web page. - ZeroBone

2 answers 2

Updated .

Coordinates relative to the document, not the window!

Version 1, cross-browser.

 <!DOCTYPE html> <html> <head> <title>titile</title> <meta charset="utf-8"> <style> body, html { height: 2000px; } </style> <script> function imgclick(id) { var elem = document.getElementsByTagName('img')[id]; function getCoords(elem) { // (1) var box = elem.getBoundingClientRect(); var body = document.body; var docEl = document.documentElement; // (2) var scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop; var scrollLeft = window.pageXOffset || docEl.scrollLeft || body.scrollLeft; // (3) var clientTop = docEl.clientTop || body.clientTop || 0; var clientLeft = docEl.clientLeft || body.clientLeft || 0; // (4) var top = box.top + scrollTop - clientTop; var left = box.left + scrollLeft - clientLeft; return { top: top, left: left }; } console.log(getCoords(elem)); var d = document.createElement('div'); document.body.appendChild(d); d.innerHTML = JSON.stringify(getCoords(elem)); } </script> </head> <body> <img src="http://wiseparents.ru/wp-content/uploads/2014/08/durachitsya.png" alt="" onclick="imgclick(0)"> </body> </html> 

Version 2: more simple. There was a mistake, coor.top in chrome plows, coor.y does not plow.

 <!DOCTYPE html> <html> <head> <title>titile</title> <meta charset="utf-8"> <style> body, html { height: 2000px; } </style> <script> function imgclick(id) { var coor = document.getElementsByTagName('img')[id].getBoundingClientRect(); var d = document.createElement('div'); document.body.appendChild(d); console.log(coor.y); d.innerHTML = 'y: ' + (coor.top + pageYOffset) + ', x: ' + (coor.left + pageXOffset) + ', height: ' + coor.height + ', width: ' + coor.width; } </script> </head> <body> <img src="http://wiseparents.ru/wp-content/uploads/2014/08/durachitsya.png" alt="" onclick="imgclick(0)"> </body> </html> 

  • Result y: NaN, x: NaN, height: 370, width: 350 in the Yandex Browser. - VenZell
  • @VenZell and in chrome too. (c) Chromium - Vasily Barbashev
  • @ven Okay, dadno, stibril. - Jean-Claude
  • @ Vasily Barbashev alright, updated. - Jean-Claude
  • Thanks a lot , works great - ZeroBone
 var x = document.getElementById("").getBoundingClientRect(); alert(x.top); alert(x.left);