umma.dev

JavaScript Event Handlers

Code Snippets of DOM event handlers.

onClick

Vanilla JavaScript
<button onClick="myClickFunction()">Click Here!</button>

<script>
  function myClickFunction() {
    alert("Hello!")
  }
</script>
React/TypeScript
const MyComponent = () => {
  const onClick = (e: React.MouseEvent<HTMLButtonElement>) => {
    e.preventDefault();
    console.log("Hello");
  };
  return <button onClick={onClick}>Click Here!</button>;
};

onChange

Vanilla JavaScript
<h1>Enter a value and hit enter!</h1>
<input type="text" name="input-box" value="" onChange="myChangeFunction(this.value)"/>

<script>
  function myChangeFunction(value) {
    alert("The input change is " + value)
  }
</script>
React/TypeScript
const MyComponent = () => {
  const [value, setValue] = useState("");

  const onChange = (e: ChangeEvent<HTMLInputElement>) => {
    setValue(e.target.value);
    console.log(value);
  };
  return (
    <div>
      <input onChange={onChange} />
    </div>
  );
};

Key events

Key Down

Vanilla JavaScript
<input placeholder="Click and press down a key" />
<p id="output"></p>

<script>
  const input = document.querySelector('input')
  const log = document.getElementById('log')

  input.addEventListener('keydown', logKey)

  function logKey(e) {
    log.textContent += ` ${e.code}`;
  }
</script>
React/TypeScript
const MyComponent = () => {
  const handleKeyChange = (e: KeyboardEvent<HTMLInputElement>) => {
    if(e.key === 'y') alert ('Yes')

    if(e.key === 'n') alert ("No')
  }
  return (
    <div>
      <input type="text" onKeyPress={handleKeyChange} />
      <p>Press the key 'y' or 'n'</p>
    </div>
  )
}

Blur and Focus

Vanilla JavaScript
<form id="form">
  <label>User:
    <input type="text" placeholder="user name"/>
  </label>
  <label>Passowrd:
    <input type="text" placeholder="password"/>
  </label>
</form>

<script>
  const password = document.querySelector('input[type="password"]')

  password.addEventListener('focus', (e) => {
    e.target.style.background = "red";
  })

  password.addEventListener('blur', (e) => {
    e.target.style.background= '';
  })
</script>
React/TypeScript
const MyComponent = () => {
  const onFocus(e: FocusEvent<HTMLInputElement>) => {
    console.log('Focus here')
  }
  return (
    <form>
      <label>User:
        <input type="text" placeholder="user name"/>
      </label>
      <label>Passowrd:
        <input type="text" placeholder="password" onBlur={onFocus} onFocus={onFocus}/>
      </label>
    </form>
  )
}

Time

Vanilla JavaScript
<p>Click on the button and wait three seconds.</p>

<button onClick="setTimeout(myTimeoutFunction, 3000);">Click me and please wait.</button>

<script>
  function myTimeoutFunction() {
    alert('Was it worth the wait?');
  }
</script>
React/TypeScript
useEffect(() => {
  const timeout = setTimeout(() => {
    console.log("This will be called after 2 seconds");
  }, 2000);

  return () => clearTimeout(timeout);
}, []);

Purpose of e.preventDefault() and e.target.value

e.preventDefault()

This method cancels the event if it is cancelable (the default action which belongs to the event will not occur). For example onSubmit will prevent submitting a form.

e.target.value

e.target gives you the element that triggered the event

e.target.value retrieves the value of that element

Examples via Code Sandbox + CodePen

Vanilla JavaScript

See the Pen Untitled by ummadev (@ummadev) on CodePen.

React/TypeScript