Reputation: 497
I have a search box which is by default not autofocused. So i am putting a keypress event on the body i.e. when forward slash (/) is pressed the search box should be in focus. Although on key press it puts the search box in focus but also puts the "/" in the search box.
body.onkeypress = (e) => {
if(e.which === 47) {
searchInput.focus()
}
}
How should I fix this?
Upvotes: 0
Views: 58
Reputation: 75
<body id="body">
<input type="text" id="elementid" />
</body>
<script>
document.onkeypress = (e) => {
if (e.which === 47) {
document.getElementById("elementid").focus();
setTimeout(() => {
str = document.getElementById("elementid").value = document
.getElementById("elementid")
.value.slice(0, -1);
});
}
};
</script>
Upvotes: 0
Reputation: 5122
Use preventdefault to prevent the '/' from being typed.
Make sure you do this in your if statement, otherwise all characters get blocked.
body.onkeypress = (e) => {
if(e.which === 47) {
e.preventDefault()
searchInput.focus()
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Upvotes: 3