Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the caller event and dom element id

Tags:

<script>
function Hello(){
    var caller =  arguments.callee.caller;
    alert( caller );
}
</script>

<input type="button" id="btnHello" value="Hello" onclick="Hello()" />

How to get the button id from the the Hello function above with out passing the any argument in the Hello function

like image 259
Jineesh Avatar asked Jun 03 '09 14:06

Jineesh


People also ask

How do I find the ID of an element in an event?

You can use event.target.id in event handler to get id of element that fired an event.

How do I find DOM events?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.

How do you find the elements of an event listener?

The addEventListener() method You can add many event handlers to one element. You can add many event handlers of the same type to one element, i.e two "click" events. You can add event listeners to any DOM object not only HTML elements. i.e the window object.


1 Answers

An event object is passed to the Hello function automatically. You need to receive it as an argument and then do some cross-platform work to grab the element. A JS framework will help you out here.

function Hello(e){
    var caller = e.target || e.srcElement;
    console.log( caller );
}

EDIT
+1 Andrew's comment below. Use addEventListener and attachEvent for best practice.

like image 153
steamer25 Avatar answered Sep 24 '22 05:09

steamer25