1

Can someone please help me out with stopping bubble effect on onclick events?

I got this:

<script language="javascript">
  function1(){
    alert('test');
  }
  function2(){
    alert('test');
  }
</script>
<div onclick="function1()">
  <span onclick="function2()">test</span>
  blablablabla
</div>

Now when I click the span, I don't want function 1 to start, but just function 2. How to do this? Do I have to edit the function, or add some more global java to this?

Mbrouwer88
  • 2,182
  • 4
  • 25
  • 38

1 Answers1

5

Change your attachment of function2 to be like this:

<span onclick="function2(event)">

Then, within the function:

function function2(e) {
    if (e.stopPropagation) {
        e.stopPropagation();
    }
    else {
        e.cancelBubble = true;
    }
 }

What we're doing there:

  1. Giving the function visibility of the event object (by passing it in from the onclick.
  2. Telling it not to bubble, either by using stopPropagation (DOM standard) or cancelBubble (IE-specific)

A lot of this stuff can be made simpler by using a decent JavaScript/DOM library like jQuery, YUI, Closure, or any of several others. These smooth-over browser differences, etc.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875