Inline JavaScript Event Binding

· 1 min read · 206 Words · -Views -Comments

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:

  1. Handlers are camelCase (onClick) vs. native onclick.

  2. 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.

  3. 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>
  1. To pass the event inline, you must use the exact name event (not e). It refers to window.event.

  2. If you don’t need event specifics (e.g., preventDefault), you can pass this instead: print(this), where this is the element.

  3. 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.

Authors
Developer, digital product enthusiast, tinkerer, sharer, open source lover