KWallace
KWallace

Reputation: 1700

How to .stopProagation() in a function called via onClick()

I have a button that includes an onClick().

<input id="btn1" type=button onClick="myFunc('arg1', 'arg2', 'arg3')">

And a function:

<script type="text/javascript">
    function myFunc(a1, a2, a3) {
        //do stuff
    }
</script>

My button is contained inside a DIV container that has it's own onClick() event.

I need the DIV onClick() to fire (as it does) but NOT when the button inside it is clicked. Then I need only the button's onClick() to fire.

I've done this before by using .bind() to bind a listener event to a button, which automatically passes the event object as a parameter to the listener function, and then using e.stopPropagation().

But, functions called via HTML onClick() do not seem to have this event passed to them.

Is there a way to invoke stopProagation() within a function that is called via HTML onClick() instead of via .bind()?

Again, the ultimate goal here is to make sure that button's onClick() fires, but it's containing DIV's onClick() does not.

Upvotes: 0

Views: 123

Answers (4)

Uzbekjon
Uzbekjon

Reputation: 11813

Wanted to add a note as a comment, but there are already 2 answer that my note relates to. So, I am adding it as an answer.

Please note:

  1. event object is not accessible on all browsers. IE would expect it to be window.event.
  2. stopPropagation() function is also non IE compatible. You would have to use cancelBubble = true instead.

Instead of passing event pass event || window.event to your method and call appropriate function to stop the propagation.

<input onClick="myFunc((event || window.event), 'arg1', 'arg2', 'arg3')" ...>

Upvotes: 1

Nikhilesh K V
Nikhilesh K V

Reputation: 1480

Modify the definition of the function myFunc as::

function myFunc(ev,a1,a2,a3) {

Now you can access the methods and parameters of the event::

ev.stopPropagation();

Then, you have to pass the parameter on the onclick::

<input id="btn1" type=button onClick="myFunc(event,'arg1', 'arg2', 'arg3')">

Upvotes: 1

lampyridae
lampyridae

Reputation: 991

You can do this:

<input id="btn1" type="button" onClick="myFunc('arg1', 'arg2', 'arg3'); event.stopPropagation();">

An event object aptly called "event" is available in handlers defined by on- prefixed HTML attributes.

Source: MDN

Upvotes: 1

t1m0n
t1m0n

Reputation: 3431

Try to pass event as first argument:

function test (e) {
    e.stopPropagation();
    console.log('click button');
}

function testDiv (e) {
    console.log('click div');
}
<div onClick="testDiv()">
    <button onClick="test(event, 'a','b','c')">button</button>
</div>

Upvotes: 3

Related Questions