When using tab button to navigate through page, when curser is at anchor tag link and on entering space button when at anchor tag link, I have to make the space button act as a enter key click using JavaScript or jQuery
Asked
Active
Viewed 286 times
-2
-
Possible duplicate of [Disable scroll down when spacebar is pressed on firefox](http://stackoverflow.com/questions/18522864/disable-scroll-down-when-spacebar-is-pressed-on-firefox) – Robiseb Oct 13 '16 at 11:15
-
@Robiseb after preventing default behaviour, I want space bar to work as a enter key – Kitty Oct 13 '16 at 11:28
2 Answers
1
I'm showing it using jQuery, the principle is the same - add a listener to the space key press, prevent default behaviour and call the function you'd like to use -
$(window).keypress(function (e) {
if (e.keyCode === 0 || e.keyCode === 32) {
e.preventDefault()
console.log('space pressed') // here comes your logic
}
});

alexunder
- 2,075
- 3
- 16
- 29
0
You can enable / disable the key listener as you want, for exemple when an input is focused.
Do like this
var input = document.getElementById('input');
input.addEventListener('focus', function(){
disableSpace(false);
});
input.addEventListener('blur', function(){
disableSpace(true);
});
function disableSpace(enable){
$(window).keypress(function(e) {
if (!enable) return true;
if (e.keyCode === 0 || e.keyCode === 32) {
e.preventDefault()
console.log('space pressed');
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input" type="text" >

Robiseb
- 1,576
- 2
- 14
- 17