Perform action by pressing key

Asked

Viewed 819 times

0

I need that when the user presses the DOWN key (down) of the keyboard, it goes to a div, in the same way as with scrollTop. Someone has done something like this using Jquery?

It would be something like this?

$(window).trigger('keydown', function (e) {
    if (e.which != 40) return false;
    var posicao = $('.homeBaixoRodapeTexto1').position().top;
    $('html, body').stop().animate({
        scrollTop: posicao
    }, 1500);
});
  • 2

    https://api.jquery.com/keydown/ the DOWN Key code is 40. After that you only need to set scrollTop or scrolldown.

  • Thank you, I edited my question.

1 answer

4


What you need to know is the position of the element you want to scroll to. This value can be found with the method .position() jquery:

var posicao = $('#destino').position().top;

To run the scroll only when the down key is pressed you can use so:

$(window).on('keydown', function (e) {
    if (e.which != 40) return false;

To use a smooth scroll you can use jQuery Animate() where you can turn off the speed in the second parameter of the function (in milliseconds). In this case I put 1 and a half seconds.

$('html, body').stop().animate({
    scrollTop: posicao
}, 1500);

Demo

The code I put in the demo:

$(window).on('keydown', function (e) {
    if (e.which != 40) return false;
    var posicao = $('#destino').position().top;
    $('html, body').stop().animate({
        scrollTop: posicao
    }, 1500);
});

Take a look in this question/answer which is related to yours if you want to see more examples of scrollTo.

  • 1

    Thank you @Sergio. I made it based on the demo you posted. Only when I press the DOWN key it does nothing. A div homeBaixoRodapeTexto1 That’s where I want him to end up.

  • @Felipestoker, put your code in jsFiddle and I’ll take a look and help if it still doesn’t work.

  • I don’t know how to put all the HTML, because the code is huge, I put the part of what I really need. When you press DOWN (Key down the keyboard) it goes to the div .homeBaixoRodapeTexto1 http://jsfiddle.net/felipestoker/3fHvf/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.