-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathunshiftjavascript.txt
35 lines (28 loc) · 1.1 KB
/
unshiftjavascript.txt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
const list = document.querySelector('.output ul');
const searchInput = document.querySelector('.output input');
const searchBtn = document.querySelector('.output button');
list.textContent = "";
const myHistory = [];
const MAX_HISTORY = 5;
searchBtn.onclick = () => {
// we will only allow a term to be entered if the search input isn't empty
if (searchInput.value !== '') {
myHistory.unshift(searchInput.value);
// empty the list so that we don't display duplicate entries
// the display is regenerated every time a search term is entered.
list.textContent = "";
// loop through the array, and display all the search terms in the list
for (const itemText of myHistory) {
const listItem = document.createElement('li');
listItem.textContent = itemText;
list.appendChild(listItem);
}
// If the array length is 5 or more, remove the oldest search term
if (myHistory.length >= MAX_HISTORY) {
myHistory.pop();
}
// empty the search input and focus it, ready for the next term to be entered
searchInput.value = '';
searchInput.focus();
}
}