Get ID of element that called a function

JavascriptEventsDom Events

Javascript Problem Overview


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.

Javascript Solutions


Solution 1 - Javascript

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>

Solution 2 - Javascript

I'm surprised that nobody has mentioned the use of this in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener or attachEvent to install your event handler, then you can make the value of this automatically be assigned to the object the created the event.

Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.

Here's how you would do that in your code in plain javascript:

Remove the onmouseover="zoom()" from your HTML and install the event handler in your javascript like this:

// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
    if (typeof obj == "string") {
        obj = document.getElementById(obj);
    }
    if (obj.addEventListener) {
        return(obj.addEventListener(name, fn));
    } else if (obj.attachEvent) {
        return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
    }
}

function zoom() {
    // you can use "this" here to refer to the object that caused the event
    // this here will refer to the calling object (which in this case is the <map>)
    console.log(this.id);
    document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}

// register your event handler
setEventHandler("nose", "mouseover", zoom);

Solution 3 - Javascript

You can use 'this' in event handler:

document.getElementById("preview").onmouseover = function() {
    alert(this.id);
}

Or pass event object to handler as follows:

document.getElementById("preview").onmouseover = function(evt) {
    alert(evt.target.id);
}

It's recommended to use attachEvent(for IE < 9)/addEventListener(IE9 and other browsers) to attach events. Example above is for brevity.

function myHandler(evt) {
    alert(evt.target.id);
}

var el = document.getElementById("preview");
if (el.addEventListener){
    el.addEventListener('click', myHandler, false); 
} else if (el.attachEvent){
    el.attachEvent('onclick', myHandler);
}

Solution 4 - Javascript

You can code the handler setup like this:

<area id="nose" shape="rect" coords="280,240,330,275" onmouseover="zoom.call(this)"/>

Then this in your handler will refer to the element. Now, I'll offer the caveat that I'm not 100% sure what happens when you've got a handler in an <area> tag, largely because I haven't seen an <area> tag in like a decade or so. I think it should give you the image tag, but that could be wrong.

edit — yes, it's wrong - you get the <area> tag, not the <img>. So you'll have to get that element's parent (the map), and then find the image that's using it (that is, the <img> whose "usemap" attribute refers to the map's name).

edit again — except it doesn't matter because you want the area's "id" durr. Sorry for not reading correctly.

Solution 5 - Javascript

I know you don't want a jQuery solution but including javascript inside HTML is a big no no.

I mean you can do it but there are lots of reasons why you shouldn't (read up on unobtrusive javascript if you want the details).

So in the interest of other people who may see this question, here is the jQuery solution:

$(document).ready(function() {
  $('area').mouseover(function(event) {
    $('#preview').attr('src', 'images/' + $(event.srcElement).attr('id'));
  });
});

The major benefit is you don't mix javascript code with HTML. Further more, you only need to write this once and it will work for all tags as opposed to having to specify the handler for each separately.

Additional benefit is that every jQuery handler receives an event object that contains a lot of useful data - such as the source of the event, type of the event and so on making it much easier to write the kind of code you are after.

Finally since it's jQuery you don't need to think about cross-browser stuff - a major benefit especially when dealing with events.

Solution 6 - Javascript

i also want this to happen , so just pass the id of the element in the called function and used in my js file :

function copy(i,n)
{
 var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range); 
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}

Solution 7 - Javascript

For others unexpectedly getting the Window element, a common pitfall:

<a href="javascript:myfunction(this)">click here</a>

which actually scopes this to the Window object. Instead:

<a href="javascript:nop()" onclick="myfunction(this)">click here</a>

passes the a object as expected. (nop() is just any empty function.)

Solution 8 - Javascript

If you setup a listener like this:

buttons = document.getElementsByClassName("btn-group")
for(let i=0;i<buttons.length;i++){
  buttons[i].addEventListener("click", (e) => { btnClicked(e);},false);
}

then you can get the id like this:

function btnClicked(e){
  console.log(e.target.id)
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAmbo100View Question on Stackoverflow
Solution 1 - JavascriptJames SumnersView Answer on Stackoverflow
Solution 2 - Javascriptjfriend00View Answer on Stackoverflow
Solution 3 - JavascriptmixelView Answer on Stackoverflow
Solution 4 - JavascriptPointyView Answer on Stackoverflow
Solution 5 - JavascriptGregory MostizkyView Answer on Stackoverflow
Solution 6 - JavascriptSuraj GuptaView Answer on Stackoverflow
Solution 7 - JavascriptRogerView Answer on Stackoverflow
Solution 8 - JavascriptkztdView Answer on Stackoverflow