Smooth page scrolling js. Javascript fading - fading colors


Document.querySelector("nav").addEventListener("click", function (e) ( var dest = e.target.href if (!dest || !(dest = dest.split("#"))) return e .preventDefault() var p = document.querySelector("main") var a = document.getElementById(dest) var st = p.scrollTop var d = a.getBoundingClientRect().top - p.getBoundingClientRect().top - 8 var s = d / 1000 var pt = performance.now() requestAnimationFrame(function f(t) ( console.log((p.scrollTop = st + d * (t - pt) / 1000), (st + d)) var cur = p.scrollTop = st + s * (t - pt) if (s<0 ? cur >st+d: cur< st + d) requestAnimationFrame(f) else requestAnimationFrame(() =>p.scrollTop = st + d) )) )); * ( box-sizing: border-box; ) nav ( position: sticky; width: 1.25em; float: left; margin: 8px; ) a ( display: block; line-height: 1.25em; text-align: center; ) a:hover ( background: silver; ) html, body, main ( height: 100%; margin: 0; ) main ( overflow: auto; ) h1 ( margin: 16px 0; background: antiquewhite; )

1

2

Whether there is a smooth scroll between anchors in pure JS? Interested in whether there is a script for smooth scrolling on pure JS, I do the site without using jQuery

3

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

4

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

5

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

6

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

7

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

8

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

9

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

10

Is there a smooth scroll between anchors in pure JS? I'm wondering if there is a script for smooth scrolling on pure JS, I'm making a site without using jQuery

Good afternoon. Today I want to tell you about such an interesting effect as smooth scrolling to anchor. For example, it can be a menu at the top of the page, when clicked, it will smoothly scroll to the corresponding element.

Surely you have seen a similar effect on other landing pages. Today you will learn how to implement it.

Smooth scrolling to anchor with javascript

In one of the projects, just the task was to implement a similar effect with smooth scrolling to a specific element when clicking on one of the menu items.

Let's start by connecting jquery library to our project and write the path to the script that is responsible for smooth scrolling:

Dealt with it. Now you need to put labels and anchors to which scrolling will occur.

I will use the example of the menu that was in the project for renting professional equipment for construction and cleaning work. Here it is source:

As you can see, everything is standard and without tricks. On the landing, later, blocks corresponding to the menu were made. They provided a specific service. To these blocks and it was necessary to do smooth transition.

In order to navigate to the desired place on the site, just add a link to the identifier desired block. Let's do that.

Now you need to set the identifiers "cleaning", "building", "actions" to the corresponding blocks. For me it looked like this:

Notice the name="cleaning" attribute. It must match the ID. Here is the script itself:

$(function () ( $("a.scrollto").click(function () ( let elementClick = $(this).attr("href") let destination = $(elementClick).offset().top; $ ("html:not(:animated),body:not(:animated)").animate(( scrollTop: destination ), 1100); return false; )); ));

If, like me, you need to implement scrolling to multiple elements, then just put the IDs like that and that's it! Highly convenient way and easy to implement. I do not claim that it is the best, but it works. If someone can simplify it, shorten it, or somehow improve it, I will be very grateful to you. As for me, so this effect may be useful to many.

Please note that at the beginning of the article we indicated the name and path of the script as follows:

That is, you need to create a folder in the root of your site called js and place a file called perehod.js in it. And already insert the script code into it. This is me, just in case. Suddenly someone does not understand.

And for today, that's all. Now you know how to implement such a cool effect as smooth scrolling of the page to the anchor. Bye everyone!

P.S.: Thank you to those who responded to the call in social networks help with ideas for new articles. I don’t know why you decided to write in private messages, leave it better in the comments, so it will be easier for other people to write a review if they see that someone more courageous has already done it.

At this method there is a drawback, it does not work well with wow.js, which we used when creating the animation in the article. Some animations do not play and remain in their place empty place. If anyone knows how to fix this, please write in the comments or in

As you probably guessed, the article will not talk about tulips and roses, not about how to get an apple tree out of a chamomile (so young Michurinians are not here :-), but we will talk about changing the color of web page elements, about smooth the flow of one color into another, i.e. Let's talk about fade effects.

Example

Let's start with an example: move the cursor over the picture, and then move the cursor away.

If you are not interested in theoretical details, but you need a ready-made solution, then you.

Formulation of the problem

Two colors are given: a start color and an end color.

It is necessary to find intermediate colors, applying which in turn to the element on the page, we will get a smooth transition from the initial color to the final one. And you should also find out how many of these intermediate colors should be and after what time there should be a change from one intermediate color to another.

Looking deeper into the issue

Let's take as the initial color, for example, white (white), and as the final color, orange-red (orangered).

#FFFFFF ? ...n... ? #FF4500

Now you need to find intermediate colors. Good. But how?! From what side to approach this issue? To do this, let's remember (or find out :-) how color is formed on the monitor screen. Any color on the monitor screen is formed from three primary colors: red ( Red), green ( Green) and blue ( Blue), by mixing them (i.e. using the RGB color model). And the colors on the web page are specified either by numerical values ​​in the same RGB system, or by literals of named colors (for example, White for white, Red for red, etc., but not all colors have names), which, anyway, indicate numerical values. But we will not consider setting a color by name, because the names were invented for the convenience of remembering a person, but in our case they will create inconvenience in calculations, because would still require conversion to numerical form. There are two ways to set a numerical color value: hexadecimal and functional.

  • In hexadecimal notation, an RGB value entry has the following format: a "#" character, immediately followed by three or six hexadecimal characters. A three-digit RGB value (#rgb) is converted to a six-digit sequence (#rrggbb) by duplicating the digits rather than adding zeros. For example, #fb0 expands to #ffbb00. Therefore, white (#ffffff) can be specified in a shorter form (#fff).
  • In functional notation, the RGB value format is as follows: the string "rgb(", immediately followed by a list of three comma-separated real (or integer, or percentage) values, immediately followed by the parenthesis ")". The integer value 255 is equivalent to a percentage value of 100% and hexadecimal values F or FF so rgb(255,255,255) = rgb(100%,100%,100%) = #FFF.

Thus, a color given in numerical form gives us the values ​​of its constituent colors, which ultimately gives us the opportunity, by changing each of the primary colors of the original color, to come to the second, final color. If we consider our specific example, then we have the following (values ​​in decimal system are indicated in brackets):

#FFFFFF = FF (255) FF (255) FF (255)
0 – CE (206) – FF (255)
#FF4500 = FF (255) 45 (49) 0

Those. in order to from white color to get orange-red, you need to leave the red component of the white color unchanged (change the value to zero), subtract 206 from green, and subtract 255 from blue. Let's call these numbers (ΔR = 0, ΔG = -206, ΔB = -255) increments.

Now, to get, for example, two intermediate colors + final color (3 in total), you need to change the initial values ​​of the RGB triplet (#FFFFFF) not by the full increments ΔR, ΔG, ΔB, but first by 1/3, then by 2 / 3 and finally 3/3 (3/3 = 1, this is the total value of the increment to obtain the final color, which, in principle, is already known to us).

#FFFFFF = FF (255) FF (255) FF (255)
#FFBAAA = 255 -0 255 - 206*1/3 = 186 (BA) 255 - 255*1/3 = 170 (AA)
#FF7655 = 255 - 0 255 - 206*2/3 = 118 (76) 255 - 255*2/3 = 85 (55)
#FF4500 = FF (255) 45 (49) 0

So, we have learned how to calculate intermediate colors. It remains to clarify one more nuance, in order for a person to notice intermediate colors, you need to make time delays between changing colors, otherwise the changes will happen so quickly that the user simply will not notice the intermediate colors.

Now we have a clear overall picture and we can move on to writing code. There are start and end colors, we can calculate n intermediate colors (where n is arbitrary), and there is a delay value t (where t is arbitrary). So the algorithm is: we assign the first intermediate color to the element on the web page, we delay by the amount t, we assign the second intermediate color to the element, we delay, ..., we assign the nth intermediate color to the element, which is the final color.

Implementation

As an example, let's make a button that, when clicked, changes the background from white to orange-red.

Let's go... The first wrong thought that may come to mind is to calculate intermediate colors in a loop, making a delay after each iteration.

Function fade() ( for (var i = 1; i<= n; i++) { кнопка.style.backgroundColor = текущий_промежуточный_цвет(i); задержка(t); } } ...

Why wrong? Because it's impossible to pause the execution of Javascript code! However, it is possible to emulate the delay using the setInterval or setTimeout methods. These methods execute Javascript code with a delay of the specified number of milliseconds (setInterval executes the code repeatedly after the specified time interval, while setTimeout executes once after the specified time has elapsed). The upper loop can be represented as follows:

Vari = 0; function fade() ( i++; //change intermediate color index //set the i-th color as the background color of the button button.style.backgroundColor = current_intermediate_color(i); if (i< n) setTimeout(fade, t); } ...

The complete example looks like this:

I hope that you understand the essence of the process, because. the example above is more for teaching than for real use. This example is designed to fade one object in one direction, as parameters are hard-coded in the form of global variables and element id. How to implement independent processes for different elements? How to interrupt the fading process and return, just as smoothly, to the original color?

Below is a functionally complete code that solves the problems posed, but now I want to clarify the answer to the second question a little. How to return from the intermediate color, which the process managed to reach, to the initial one, should be clear. But how to stop an already running process? As you remember, the process is implemented by calling the setTimeout method, so the answer to the question is to cancel the setTimeout method. When setTimeout() is called, it returns a value that is a pointer to this "timeout", and to cancel it, you need to call the clearTimeout() method, which is passed as a parameter a pointer to the "timeout" returned by the setTimeout method.

Turnkey solution

fade.js library. An example of its use is below.

  • Fade
  • Fade
  • Fade

Basic steps:

  1. We connect the library of functions;
  2. We define the rules;
  3. We call the method fade() to blend color from start to end, or fade.back() to return to the original color.

Chewing

How to connect the library, I think, can be seen from the example above. Now it is worth explaining the definition of the rules. Before calling fading, you need to define the rules by which it will be performed: you need to define the start and end colors, you also need to determine how many intermediate colors need to be generated between the start and end colors; you need to know which CSS property of the element to apply the generated colors to, as well as what time delay to do before changing one intermediate color to another.

Rules are defined using the method fade.addRule

Syntax: fade.addRule(sRuleName, sFadeStartColor, sFadeFinishColor, sCSSProp, nMiddleColors, nDelay)

Arguments:

  • sRuleName - rule name, set arbitrarily;
  • sFadeStartColor and sFadeFinishColor - start and end colors specified in hexadecimal form (full or abbreviated) ;
  • sCSSProp - CSS color property to be changed;
  • nMiddleColors - number of intermediate colors (optional argument, default is 50) ;
  • nDelay - delay between changing intermediate colors in milliseconds (optional argument, default is 1).

The fading call itself is done through the fade(sElemId, sRule) and fade.back(sElemId, sRule) methods, where sElemId is the element id, and sRule is a comma-separated list of rules.

On one of the sites, it was necessary to implement scrolling (scrolling) the page up with smooth animation. In jquery, this is done with one command:

$("html,body").animate((scrollTop:0),500);

And in pure javascript, it's a little more complicated:

vart;
function scrolltop() (
var top = Math.max(document.body.scrollTop,document.documentElement.scrollTop);
if(top>0) (
window.scrollTo(0,Math.floor(top/1.5));
t = setTimeout("scrolltop()",30);
) else (
clearTimeout(t);
}
return false;
}

Variable top equals the current page scroll distance in pixels. Every 30 ms, this value decreases by 1.5 times, eventually gradually reaching zero. This is an imitation of the ease-out property in CSS animations.

If you need to scroll the page up linearly, without acceleration, then we write something like this:

window.scrollTo(0,-20);

Then the page will scroll to the top at a speed of 20 pixels in 30 ms.

What causes a period of 30 ms? The comfortable screen refresh rate is approximately 30 frames per second, which means that the duration of each frame is 30 ms. For ideal smoothness, you can do 60 frames per second, and then the timeouts should be about 15 ms. But it can be annoying on weak devices.

Thanks to the author of the site

If you want to support the project, use the Yandex.Money platform - it's confidential and safe.







2022 gtavrl.ru.