Last Updated:

Scroll through content within a block in Javascrip


When creating a site, it is very often necessary to implement vertical scrolling of content within the block. Many of you will say that there is nothing easier, it is enough to set a fixed height of the block and set its property to value or . Indeed, this is quite enough, but, in most cases, scroll bars violate the design of the web page.<DIV>overflow-yautoscroll

In this article, I will tell you how to scroll through the content in the block and the scrollbar itself using JavaScript using the event. Let's take a closer look at html layout, CSS and the code itself in pure JavaScript.scroll

Let's draw up a technical task for creating a scrolling content inside the block:

  1. Scrolling should be done with the mouse wheel when hovering over the selected block or dragging the scrollbar slider.
  2. A block should have a custom scrollbar with a slider height depending on the size of the content inside the block.
  3. When scrolling through content in a block, use the standard scroll event.
  4. A page can have multiple blocks with scrolling content.
  5. The width and height of scrolling blocks should not affect the operation of the script.

HTML markup of the scrolling block.

HTML code of the block with scrolling content:

Let's take a quick look at the purpose of each element:

The parent element specifies the width, height and design of the block with scrolling content.
A viewing area that defines content boundaries beyond which content is not visible. In addition, the viewport clips and makes invisible the default scroll bar of the container.
The container in which the content is placed and will be scrolled. It is in this container that the standard scroll bar will be replaced with a custom one.

Please note that we have banned the display of the default scroll bar, but we did not do the HTML layout of the custom scrollbar. It will be generated by the JS script if necessary, i.e., if the height of the content is greater than the height of the container. Such a solution provides great flexibility in application, there is no dependence on the height of the content. This is convenient when there are several such blocks on the page with different content.


The style sheet for the scrolling block.

Below I will give only those styles that directly relate to the block with scrolling content.

Very important.
To reduce the size of the style sheet, I will not list properties with vendor prefixes that provide cross-browser compatibility. Do not forget to prescribe them when implementing your projects.

Start writing JavaScript for the block with scrolling content.

The first thing we will do is create an anonymous self-starting function, within which our code will be located. It is necessary to make it a rule to limit the scope of the script in order to exclude conflicts with other JS scripts connected to the page.

When writing a JS script, we will use the Class construct. This allows you to create multiple instances of scrolling blocks on a single page.

Instantiates blocks with scrolling content.

First of all, let's create a collection of blocks in which you may need to scroll through the content. Next, using the method, we will go through the resulting collection, while we will perform the following actions:for...of

  1. create an instance of the current block using the class constructor ScrollBox;
  2. create an HTML layout of the scrollbar if the height of the content in the current block is greater than the height of the parent container.
  3. Let's register the event handlers.


We will write all further JS code inside the .class ScrollBox { ... }

First of all, consider the class constructor. The constructor initializes a number of objects and variables containing information about the scroll block instance. As an argument, the constructor takes a block object with content that is currently being instantiated. ScrollBox

In addition to the initiated variables, we need to add a constant that is a private static field. This constant will store the minimum height of the scroll bar slider.

The constructor, in addition to initializing objects and variables, calls the . The algorithm of this function:init()

  • 1

    Compares the height of the content to the height of the viewport. If the height of the content is less than or equal to the height of the viewport, the function stops working, because there is no need for scrolling.

  • 2

    Specifies the maximum scrolling of content.

  • 3

    Calculates the ratio between the heights of the viewport and the content.

  • 4

    Calls a function to create a scroll bar.createScrollbar()

  • 5

    Calls a function that registers event handlers to control both scrolling by rotating the mouse wheel and dragging the scrollbar slider.registerEventsHandler()

Let's look at the function code and the comments to it:init()

Create a scrollbar for a block with scrolling content.

As I wrote above, the scrollbar and its slider are formed using the .
Let's consider the algorithm of this function:

  • 1

    Using the built-in JavaScript method, it creates new DOM elements from which a scroll bar and a slider will be formed.document.createElementDIV

  • 2

    Assigns classes to the created elements— and accordingly.scrollbarscroller

  • 3

    Inserts the created items into the viewport.

  • 4

    Gets the DOM object of the scroll bar slider, calculates and sets its height.

The height of the slider depends on the ratio of the heights of the viewport and the content (coefficient), and the greater the height of the content, the lower the height of the scroll bar slider.ratio

Function code and comments to it:createScrollbar()

Now you need to register event handlers that will control the scrolling of content inside the viewport.

Register event handlers for the scrolling content block.

Event handlers are registered in the function called from the function discussed earlier. The handler is assigned by calling a method that binds to the element on which the event is logged.registerEventsHandler()init()addEventListener

Remember, this is very important.
When you use the method, you lose the call context - , which refers to the current object. Using the built-in JavaScript method, you can directly pass the call context to the event handler function. addEventListenerthisbind

We will register the following events:

rotation of the mouse wheel, while the cursor should be above the viewport;
Pressing the left mouse button when the cursor is on the slider;
moving the mouse along the scroll bar and the document as a whole, that is, if the cursor leaves the scroll bar area when moving, the slider will not be interrupted;
release the left mouse button, and the cursor can be over any part of the document.

Function code and comments to it:registerEventsHandler()

As you can see from the code, the event is bound to the element . But events are tied to the object , that is, the event can occur when the cursor positions above any part of the page. This behavior is provided when the content is defaulted to scroll within the block when assigning a style to it. Logically, I tried to keep it.mousedownscrollermousemovemouseupdocumentoverflow-y: scroll

Control the scrolling of content inside the block by the 'scroll' event.

When the event occurs, scrolling will be done by standard methods built into the browser. We only need to change the position of the slider.
We will change the position of the slider by changing the value of the property in proportion to the change in the value of the current scrolling of the content, taking into account the coefficient obtained earlier. Let's take another look at the function that is called when an event occurs:

Next, I'll show you how to drag the slider along the scroll bar and how the scrolling content changes depending on the current position of the slider.

Scroll through content by moving the scrollbar slider.

Dragging the slider begins with the occurrence of the event. When processing this event, the coordinate along the y-axis is remembered, which will be considered the starting point of the slider movement. In addition, a flag is set to signal the click of the left mouse button.
The JS code that implements this is in a function that is the second parameter of the event handler log provider. Let me remind you of this code so that you do not turn the page:

The drag of the slider is the responsibility of the function , which is called when an event occurs. Let's look at the algorithm of this function:dropmousemove

  • 1

    Verifies that the left mouse click flag has been set. If the flag is not set, it stops working.pressed

  • 2

    Calculates the amount of mouse movement as the difference between the start coordinate and the current cursor coordinate on the Y-axis .this.starte.clientY

  • 3

    Changes the position of the slider by the amount of cursor movement, changing its vertical offset by changing the CSS property .top

  • 4

    Restricts the movement of the slider to the top and bottom border of the viewport.

  • 5

    Scrolls through the content by an amount proportional to the movement of the slider.

  • 6

    Sets the Y coordinate of the beginning of mouse movement to the current Y coordinate.

Before we start writing the code of the function , let's take a closer look at p. 4 of the presented algorithm.drop

Previously, we obtained the maximum possible displacement of the slider from the upper border of the viewport - , calculated as the difference in the height of the viewport and the height of the slider. Let's take a look at the picture:scrollerMaxOffset


From the figure you can see that if you try to further increase the displacement of the slider, then its lower part will go beyond the viewport. In other words, the sum of the height of the slider and its displacement should not exceed the height of the viewport.

In order for the slider not to go beyond the upper boundary of the viewport, it is necessary to control that its displacement from this border is greater than or equal to zero.

Now you can present the complete code of the function :drop

When you release the left mouse button, an event occurs and dragging the scrollbar slider stops. When you do this, the flag is set to .mouseuppressedfalse

Let me remind you of this code so that you do not turn the page:

At this point, the study of scrolling content in the block can be considered complete. You can see an example of various options for scrolling the block, download the HTML layout and the full JS code by following the links indicated at the beginning of the page.