Inline JavaScript Event Binding
Frameworks are popular and make JS easy to use, but they can also hide fundamentals. Inline JS event binding is less common in modern code, but it’s important to understand.
Event binding in React
React smooths over some details:
Handlers are camelCase (
onClick
) vs. nativeonclick
.Binding handlers across a list doesn’t inherently waste performance — React uses event delegation under the hood. Still, per‑item handlers can hurt readability/maintenance.
Event objects are passed to handlers (name is arbitrary):
<Button onClick={this.handleClickCancel}> <GlobalI18n.CANCEL /> </Button> private handleClickCancel = (e) => this.props.callback(e.target.id);
Native inline event binding
Inline usage looks like this:
<p id="p">selectedIndex: <span>0</span></p>
<select id="select" onchange="print(event)">
<option selected>Option A</option>
<option>Option B</option>
<option>Option C</option>
<option>Option D</option>
<option>Option E</option>
</select>
<script>
var selectedIndexEle = document
.getElementById('p')
.querySelector('span');
function print({ target: e }) {
selectedIndexEle.innerText = e.selectedIndex;
}
</script>
To pass the event inline, you must use the exact name
event
(note
). It refers towindow.event
.If you don’t need event specifics (e.g., preventDefault), you can pass
this
instead:print(this)
, wherethis
is the element.Alternatively, bind in a script block and receive the event explicitly, similar to React.
document .getElementById('select') .addEventListener('change', function (e) { print(e); });
Final Thoughts
Simple but foundational — worth knowing even if you use frameworks.