Code Snippets of DOM event handlers.
<button onClick="myClickFunction()">Click Here!</button>
<script>
function myClickFunction() {
alert("Hello!")
}
</script>
const MyComponent = () => {
const onClick = (e: React.MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
console.log("Hello");
};
return <button onClick={onClick}>Click Here!</button>;
};
<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>
const MyComponent = () => {
const [value, setValue] = useState("");
const onChange = (e: ChangeEvent<HTMLInputElement>) => {
setValue(e.target.value);
console.log(value);
};
return (
<div>
<input onChange={onChange} />
</div>
);
};
<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>
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>
)
}
<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>
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>
)
}
<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>
useEffect(() => {
const timeout = setTimeout(() => {
console.log("This will be called after 2 seconds");
}, 2000);
return () => clearTimeout(timeout);
}, []);
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
gives you the element that triggered the event
e.target.value
retrieves the value of that element
See the Pen Untitled by ummadev (@ummadev) on CodePen.