jQuery and stopPropagation

Often you might not even notice the following problem: Imagine you got a table row or a list element including several links. By default you defined a function like

$('table tr').click(function(event) {
  target = $(this).find('a:first').attr('href');
  open(target, '_self');
})

In this case the function finds the first defined link in our row and links it to the row itself.
If we click on the link, we get redirected to the defined target. But as the link is lying in our linked row, this click will also be executed and our target is loaded twice. Even though the user won’t notice it, functions like deleting or answering will throw errors.
jQuery got a very nice core function to suppress the second loading.

stopPropagation()

We are using this function to stop the propagation of our click-event like shown:

$('table tr').click(function(event) {
  target = $(this).find('a:first').attr('href');
  open(target, '_self');
})
$('table tr a').click(function(event) {
  event.stopPropagation();
})

It reminds me of a “return false;”. Just look for the bind function here:
jQuery API Browser. There you may find more details on similiar cases, too.

UPDATE for Internet Explorer

As this won’t work in MS’ IE, you have to use the similar

event.cancelBubble = true;

(Source)

If you put both behind each other, IE would still throw some errors. So you should try following if-function if you are using jQuery:

    agent = jQuery.browser;
	if(agent.msie) {
		event.cancelBubble = true;
	} else {
		event.stopPropagation();
	}
  1. Bart McLeod says:

    I read somewhere that stopPropagation and friends are not implemented for custom events, like tabselect… Any ideas?

  2. Jim Schmid says:

    You made my day.

Leave a Reply
  1. (required)
  2. (will not be published) (required)