English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

jQuery scrollLeft() Method

jQuery HTML/CSS Methods

The scrollLeft() method gets or sets the horizontal scrollbar position of the selected element.

When using the scrollLeft() methodGetwhen the position is set, it will returnthe first selected elementthe horizontal position of the scrollbar.

When using the scrollLeft() methodSetwhen the position is set, it will beAll selected elementsSet the horizontal position of the scrollbar.

Syntax:

Get the horizontal scrollbar position:

$.scrollLeft(selector)

Set the horizontal scrollbar position:

$.scrollLeft(selector, value)

Example

Get the scrollLeft of DIV:

$("div").scroll(function(){
  $(this).scrollLeft();
});
Test and see‹/›

Set the scrollLeft of DIV:

$("button").click(function(){
  $("div").scrollLeft(150);
});
Test and see‹/›

Set the document's scrollLeft:

$("button").click(function(){
  $(document).scrollLeft(300);
});
Test and see‹/›

Add smooth scrolling when the user scrolls the page:

let size = $(".main").outerWidth(); // Get the width of ".main"
$(window).keydown(function(event) {
  if(event.which === 39) { // If the right arrow key is pressed
    $("html, body").animate({scrollLeft: "+=" + size}, 250);
  } else if(event.which === 37) { // If the left arrow key is pressed
    $("html, body").animate({scrollLeft: "-=" + size}, 250);
  }
});
Test and see‹/›

Parameter Value

ParameterDescription
valueAn integer indicating the new position to which the scrollbar will be set

jQuery HTML/CSS Methods