glen maxwell
glen maxwell

Reputation: 203

How do make div to scroll on key up and down using jquery

Here is the link of JSFIDDLE. I'm trying to scroll within dialog box using up and down key. I can scroll by using mouse, but came to know how do scroll up and down using keys. Here is what I am trying so far.

var element = document.getElementById("scroll-to-here");
        element.scrollIntoView({block: "end", behavior: "smooth"});

Actually I'm trying to scroll 15px; or 20px up or down on key up and down.

Upvotes: 0

Views: 2252

Answers (2)

Abdul Rafay
Abdul Rafay

Reputation: 807

try this:

$("#dialog-message").dialog({
   modal: true,
   draggable: false,
   resizable: false,
   position: ['center', 'top'],
   show: 'blind',
   hide: 'blind',
   width: 400,
   dialogClass: 'ui-dialog-osx',
   buttons: {
      "I've read and understand this": function() {
          $(this).dialog("close");
      }
   }
});

$(document).keydown(function(e) {
 switch(e.which) {

    case 38: // up
    var y = $('#to-scroll').scrollTop();  //your current y position on the page
    $('#to-scroll').scrollTop(y-150);


    break;

    case 39: // right
    break;

    case 40: // down
     var y = $('#to-scroll').scrollTop();  //your current y position on the page
       $('#to-scroll').scrollTop(y+150);


    break;

    default: return; // exit this handler for other keys
}
//e.preventDefault(); // prevent the default action (scroll / move caret)
});

see this example:

http://jsfiddle.net/db5SX/9488/

Upvotes: 0

kazinix
kazinix

Reputation: 30103

use scrollTop function:

$("#yourElement").scrollTop(10);

in your case, increase or decrease the scroll top depending on the button being pressed.

var $el = $("#yourElement");
$el.scrollTop($el.scrollTop() - 10); //move the scrollbar upwards

see this example:

https://jsfiddle.net/po6bokz6/

Upvotes: 2

Related Questions