Click handler

2 snippets across 2 stacks — JavaScript, React

JSJavaScript

Event Listeners

JS · DOM Manipulation
syntax
element.addEventListener(event, handler, options)
element.removeEventListener(event, handler)
example
const button = document.querySelector("#submit-btn");

function handleClick(event) {
  event.preventDefault();
  console.log("Button clicked!", event.target);
}

button.addEventListener("click", handleClick);

// One-time listener
button.addEventListener("click", () => {
  console.log("This fires only once");
}, { once: true });

Note The third argument can be a boolean (useCapture) or an options object { capture, once, passive, signal }. Use { once: true } for one-shot handlers.

REReact

Click Events

RE · Event Handling
syntax
<button onClick={handler}>...</button>
// With argument
<button onClick={() => handler(arg)}>...</button>
example
function ColorPicker({ colors, onSelect }) {
  return (
    <div className="palette">
      {colors.map(color => (
        <button
          key={color}
          style={{ backgroundColor: color, width: 40, height: 40 }}
          onClick={() => onSelect(color)}
          aria-label={`Select ${color}`}
        />
      ))}
    </div>
  );
}

Note Pass a function reference, not a function call. Writing onClick={handler()} would call the function during render. Use an arrow function when you need to pass arguments: onClick={() => handler(id)}.