Get ID of element that called a function

Ambo100 picture Ambo100 · Oct 2, 2011 · Viewed 152.7k times · Source

How can I get the ID of an element that called a JS function?

body.jpg is an image of a dog as the user points his/her mouse around the screen at different parts of the body an enlarged image is shown. The ID of the area element is identical to the image filename minus the folder and extension.

<div>
    <img src="images/body.jpg" usemap="#anatomy"/>
</div>

<map name="anatomy">
  <area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom()"/>
</map>

<script type="text/javascript">
function zoom()
{
 document.getElementById("preview").src="images/nose.jpg";
}
</script>

<div>
<img id="preview"/>
</div>

I've done my research and have come to Stack Overflow as a last resort. I'm prefer a solution that doesn't involve jQuery.

Answer

James Sumners picture James Sumners · Oct 2, 2011

Pass a reference to the element into the function when it is called:

<area id="nose" onmouseover="zoom(this);" />

<script>
  function zoom(ele) {
    var id = ele.id;

    console.log('area element id = ' + id);
  }
</script>