Reputation: 1700
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
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.
event
object is not accessible on all browsers. IE would expect it to be window.event
.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
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
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
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