Is there a way to scroll to top when esc key is pressed?

Viewed 352

How do i make it so that whenever i press "esc" it scrolls to the top? I have tried to use

<a name="top"></a>
<p>some text here.../p>
<a href="#top" id="backtotop">hi</a>
<script>
var input = document.getElementById("body");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 27) {
   event.preventDefault();
   document.getElementById("backtotop").click();
  }
});
</script>

but it doesn't work. If anyone could help me fix my code, that would be great! :)

4 Answers

Just use document.body.scrollTop = 0 to scroll to the top of the page. Depending on which element actually has the scrollbar, it could be document.documentElement.scrollTop = 0 too.

Example:

var input = document.getElementById("body");
input.addEventListener("keyup", function(event) {
  if (event.keyCode === 27) {
   event.preventDefault();
   document.documentElement.scrollTop = 0;
  }
});
input {
  position: relative;
  top: 200px;
}
<div>Top</div>
<input id = "body" type = "text"/>

document.body.addEventListener('keypress', function(e) {
  if (e.key == "Escape") {
    document.body.scrollTop = 0;
  }
});

document.onkeydown = function(keyPressEvent) {
  if (keyPressEvent && keyPressEvent.key && (keyPressEvent.key === "Escape" || keyPressEvent.key === "Esc") && keyPressEvent.keyCode === 27) {
    console.log('Escape key pressed!');
    // put your logic here
    document.body.scrollTop = 0;

  }
};
Escape Click Event

Note- Simple JS way to detect click event using Key & keyCode.

You can add an Event Listener in JS to detect when the esc key is pressed (Key code 27) then add

document.body.scrollTop = 0;

Example:

document.body.addEventListener('keypress', function(keypress) {
  if (keypress.keyCode === 27) {
    document.body.scrollTop = 0;
  }
});
Related