Get information about the source of an event with jQuery

Viewed 46020

A function is bound to an event for many objects. One of those objects fires the event and jQuery kicks in. How do I find out who fired the event inside the JavaScript function?

I've tried using function [name](event){} and poking at event but I get "'data' is null or not an object".

Here's my code right now:

<script type="text/javascript">
    $(document).ready(function() {
    $('.opening').bind("click", function(event) {
         //code to populate event.data since right now, the tags don't hold the info...they will eventually with an XHTML custom namespace
            event.data.building = "Student Center";
            event.data.room = "Pacific Ballroom A";
            event.data.s_time = "9/15/2009 8:00";
            event.data.e_time = "9/15/2009 10:00";

            indicatePreferenceByClick(event);
        });
    function indicatePreferenceByClick(event) {
        alert("I got clicked and all I got was this alert box.");
        $("#left").load("../ReserveSpace/PreferenceByClick", { building: event.data.building, room: event.data.room, s_time: event.data.s_time, e_time: event.data.e_time});
    };
</script>
6 Answers

event.currentTarget might be what you're looking for.

If you're asking about event source as in Java where target is the object that caused the event to be fired and source is the object to which the event handler was attached to, then this might be what you're looking for:

Within the event object which is passed to a handler when an event is fired, there are two objects include i.e. target and currentTarget.

  • target is the object that caused the event to be fired
  • currentTarget is the object where the handler was attached to

To show it in your code:

<script type="text/javascript">
  $(document).ready(function() {
    $('.opening').bind("click", function(event) {
      // ...your code
      indicatePreferenceByClick(event, event.currentTarget);
    });
    function indicatePreferenceByClick(event, eventSource) {
      alert("I got the event source.");
      console.log(eventSource);
      // ...your code
    }
  });
</script>

For more Event.currentTarget

Hope it helps :)

Related