JQuery event.target error

9.1k Views Asked by At

I've a box from divs (price_item) with several child divs (date, price etc.). I'm using it as a caroussel for showing prices. If one clicks on any child, the parent's background color must be changed to red. I wrote it like:

$(...selectquery...).click(function() {
    var $tgt = $(event.target);
    $tgt.parent().css("backgroundColor", "red");
});

on Chrome, event.target is working as expected, on Firefox 3.0.1 it says "event is not defined". How can I work around this?

I've tried the following:

$(this).parent().css()

it says 'object is not a function'

thanks!

3

There are 3 best solutions below

0
On BEST ANSWER

The event object gets passed into your click handler by jQuery, so you need to specify it as a parameter.

You also may be able to add the click handler to the parent object and use "$(this)" instead of event.target:

$(...select the parent...).click(function() {
    $(this).css("backgroundColor", "red");
});

If the user clicks the parent, or any of its children, it will call your click handler. If you need to only change the background if they actually click on one of the children (not between them, for example) this won't work.

0
On
$(...selectquery...). .click(function(event) { var $tgt = $(event.target); 

$(this).parent().css("...") should work as well
0
On

If you want to do anything with events, make sure you pass the event as an argument to the handling function:

$('#foo').click(function(event) {
  // ...
});

But ditto what the earlier poster said, you should be able to just use $(this) to get what you want.