How to stop event propagation with an inline onclick attribute?
To swiftly terminate event bubbling, use the event
object's stopPropagation()
function directly in your inline onclick
attribute like so:
This approach ensures a click event on the button doesn't bubble up to any parent elements.
Getting a grip on event propagation
Html elements with an annotated onclick
attribute establish an instant bond to that click event. But what's next if this element resides within other elements with similar onclick attributes? By default, this click event will front crawl its way upstream, triggering parent elements along the way. To sever this ripple effect, use the event.stopPropagation()
function.
Playing nice with older browsers
While event.stopPropagation()
enjoys sound compatibility with more recent browsers, there may be hitchhikers on the backward compatibility road.
This block first verifies if event.stopPropagation()
is available, before utilizing it. For the less fortunate, here's where IE8 and its compatriots come in - it defaults to setting window.event.cancelBubble = true
.
Doesn't hurt to maintain a bit
Inline event handlers can quickly turn into Lasagna code. Nesting complex logic into inline onclick
attributes can make your codebase hard to digest:
Cross-browser friendliness
Keeping things cross-compatible is crucial in web development. Some browsers, like Firefox, can be sneaky. Cover your bases and guarantee support for event
and stopPropagation()
. With smart-checks in place for the existence of necessary items, you can safely support all browser types:
The simple yet powerful solution
A sleek, dependency-free inline solution enables a <span>
's click event to steer clear of accidentally invoking a click event on an enveloping <div>
.
The solution succinctly controls the event stream without separate scripts or verbose event controllers adding complexity.
Was this article helpful?