-3

I want to implement that table rows are clickable. I implemented that by changing the cursor on hover in CSS, and by implementing a click event on the table row, which goes to the link specified in a data-href attribute.

The thing is, there are some buttons inside of table rows, which trigger an AJAX request. So, when I click on those buttons, I want the click event on the parent row to be prevented.

This is my current implementation (in CoffeeScript):

jQuery.fn.preventClick     = -> $(@).data("disabled", true)
jQuery.fn.isClickPrevented = -> $(@).data("disabled")
jQuery.fn.enableClick      = -> $(@).removeData("disabled")

$("#table tr").click ->
  window.location = $(@).data("href") unless $(@).isClickPrevented()
  $(@).enableClick()

$("#table tr").on "click", "[data-remote='true']", ->
  $(@).closest("tr").preventClick()

I'm relying on the fact that the child click event gets triggered before the parent one.

For me this looks way too complicated. Is there a more elegant way to implement this?

Janko
  • 8,985
  • 7
  • 34
  • 51

1 Answers1

2

Inside your event handler, you can prevent an event bubbling up to the ancestors by calling

e.stopPropagation();

(You'll need to accept e as the first argument of the event handler function.)

You can also do return false from an event handler, which does both stopPropagation and preventDefault.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
  • That's it! :) I'm fairly new to JavaScript and jQuery, so this was a great help. I will accept your answer when StackOverflow's minimum 10 minutes pass. – Janko Jun 19 '13 at 11:00