5

See this question. Except that the answer returns the child element when a child element is clicked, i.e. in the case that you bind a div.

<div id="parent" data-bind="click: log">Parent Div<div id="child">Child</div></div>

<script>
    var ViewModel = function() {
        this.log = function(data, event) {
            console.log("you clicked " + event.target.id);
        }
    };
    ko.applyBindings(new ViewModel());
</script>

See this fiddle

I want to get the original element the click event was bound to. Any suggestions?

Community
  • 1
  • 1
Dirk Boer
  • 8,522
  • 13
  • 63
  • 111

1 Answers1

12

event.currentTarget will give you the element to which the event is bound. Change your Console.log as below:

console.log("you clicked " + event.currentTarget.id);
Ravi Y
  • 4,296
  • 2
  • 27
  • 38
  • 2
    event.currentTarget is not available for IE8. For <= IE8 support you can use: `var target = (event.currentTarget) ? event.currentTarget : event.srcElement;` – Shital Shah Jan 26 '14 at 20:45
  • @ShitalShah: It's more complicated than that. `srcElement` is more equivalent to `target` (the *originating* element, which may be a descendant) than like `currentTarget`. So when handling delegated clicks, there's an important difference. – T.J. Crowder Feb 18 '14 at 14:23
  • I would like to add that if you console.log() out just the event in bind loop, currentTarget will be null - don't be confused, it's just because it is not currentTarget AFTER the event has passed, it is available only in listener - while event is "active" :) – jave.web Aug 31 '15 at 11:33