I want to have a single re-usable function for two events.
const inputEl = document.getElementById("input-el");
const listItems = document.getElementById("list-items");
const addBtn = document.getElementById("add-btn");
inputEl.addEventListener("keypress", function(event) {
if (event.key === "Enter"){
listItems.innerHTML = inputEl.value
}
});
addBtn.addEventListener("click", function() {
listItems.innerHTML = inputEl.value
})
<input type="text" id="input-el">
<button id="add-btn">Add to List</button>
<ul id="list-items"></ul>
The function should allow me to parse in either "Enter" key event after user presses on enter key or a "click" after user clicks on button. currently, I have two the functions for each event.
The two functions are working okay but I was wondering if there was a way to make a function that is more re-usable when listening to events.
You can simply check for either of the conditions to be true, as both function receive an event
with more info about it, so you can just ask whether it's a click event or whether the key in the event matches the key you are looking for:
event.type === 'click' || event.key === 'Enter'
Like this:
const inputEl = document.getElementById("input-el");
const listItems = document.getElementById("list-items");
const addBtn = document.getElementById("add-btn");
function addItem( event ){
if( event.type === 'click' || event.key === 'Enter' ){
event.preventDefault();
listItems.appendChild( document.createElement( 'li' ) ).textContent = inputEl.value;
}
}
inputEl.addEventListener( "keypress", addItem );
addBtn.addEventListener( "click", addItem )
<input type="text" id="input-el">
<button id="add-btn">Add to List</button>
<ul id="list-items"></ul>