Take action when pressing the key

0

I need that when the user presses the DOWN key of the keyboard, it goes to a div, in the same way as with scrollTop. Has anyone done anything like this using Jquery?

Would it 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);
});
    
asked by anonymous 17.04.2014 / 03:48

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 .position () method of jquery:

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

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

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

To use a smooth scroll you can use jQuery animate () where you can set the speed in the second function parameter (in milliseconds). In this case I put 1 second and a half.

$('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 at in this question / answer that is related to if you want to see more scrollTo examples.

    
17.04.2014 / 08:18