sdr
sdr

Reputation: 1665

JavaScript event object is not being populated in event handler function

I have the following code:

Html:

<tr>
    <td onclick="ThingClicked()">click me</td>
</tr>

JS:

function ThingClicked(event) {
    var row = event.currentTarget.parent("tr");
    callAnotherDOMManipulatingFunction(row);
}

For some reason, event.currentTarget is undefined. I tried 'this' but that was undefined aswell. What's going on? How do I get the row that this td is contained in?

Upvotes: 4

Views: 1288

Answers (4)

Peter
Peter

Reputation: 1

Try this:

<tr>
    <td onclick="ThingClicked(event)">click me</td>
</tr>

with the input parameter of your handler function specially called event and nothing else.

Upvotes: 0

user113716
user113716

Reputation: 322492

Well, since you included a jQuery tag (and included a link to jQuery docs), I'll show you how that way.

EDIT:

jQuery live() docs

jQuery clone() docs

EDIT: Added jQuery's ready() function. You will always place your code inside as shown.

$('document').ready(function() {
    $('td').click(function() {
        var row = $(this).closest('tr');
        callAnotherDOMManipulatingFunction(row);
    });
});

Of course, this will attach a click event to every td tag, but you get the idea.

EDIT:

Further explanation. When using jQuery, you typically will assign events in your javascript, not in HTML. Assigning to 'td' will give the click event to every 'td' tag on the page, so it may be that you will instead give the 'td' a class and use that to attach the event, like:

$('.myFreakingAwesomeClass').click(function() {
    ...
});

You won't often need to reference 'event', but it does come in handy at times.

Upvotes: 5

Pablo Fernandez
Pablo Fernandez

Reputation: 105220

Change your code like this:

Html:

<tr>
    <td onclick="ThingClicked(this)">click me</td>
</tr>

JS:

function ThingClicked(element) {
    callAnotherDOMManipulatingFunction(element);
}

Upvotes: 0

Nick Craver
Nick Craver

Reputation: 630429

Try this:

<tr>
  <td onclick="javascript:ThingClicked(this);">click me</td>
</tr>

function ThingClicked(td) {
    callAnotherDOMManipulatingFunction(td.parentNode);
}

Upvotes: 1

Related Questions