Anchor Links

How to Create Smooth Scrolling When Clicking an Anchor Link

Smooth scrolling allows jumping between page sections in just one click without manually scrolling up or down. To have this feature on your page will definitely be appreciated by the users. So, let’s see what methods are used to create a smooth scrolling.

scrollIntoView()

The scrollIntoView() method is used for scrolling the view of the user to the element that it is called upon. Setting this value to “smooth” for the behaviour property will make the page scroll smoothly:

html> html> head> title>Title of the Document title> style> #element < height: 200px; width: 350px; overflow: auto; > #el1 < height: 200px; width: 1000px; > #el2 < height: 100px; width: 1000px; > style> head> body> div> button onclick="scrollFunction1()"> Scroll to element-1 button> br> button onclick="scrollFunction2()"> Scroll to element-2 button> br> br> br> div id="element"> h2> Click on the scroll button h2> div id="el1"> h2>Element-1 h2> div> div id="el2"> h2>Element-2 h2> div> div> div> script> function scrollFunction1( ) < let e = document.getElementById("el1"); e.scrollIntoView(< block: 'start', behavior: 'smooth', inline: 'start' >); > function scrollFunction2( ) < let e = document.getElementById("el2"); // This ends the block to the window // bottom and also aligns the view to the center e.scrollIntoView(< block: 'end', behavior: 'smooth', inline: 'center' >); > script> body> html>

scrollTop()

The scrollTop() jQuery method is used for scrolling to a particular section of the page. Animating this method will make the scroll smoother:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> style> #textDiv < height: 1500px; > p < margin-top: 100px; height: 500px; > style> head> body> div id='linkDiv'> a href="#link1" class="scrollLink">Scroll to link1 a> a href="#link2" class="scrollLink">Scroll to link2 a> div> div id="textDiv"> p id="link1">strong>Anchor 1 strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea. p> p id="link2">strong>Anchor 2 strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas. p> div> script> $(document).ready(function( ) < $("a.scrollLink").click(function(event) < event.preventDefault(); $("html, body").animate(< scrollTop: $($(this).attr("href")).offset().top >, 500); >); >); script> body> html>

If the target element does not have an id, and you link to it by its name, you can use the following script:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> style> #textDiv < height: 1500px; > p < margin-top: 100px; height: 500px; > style> head> body> div id='linkDiv'> a href="#link1" class="scrollLink">Scroll to link1 a> a href="#link2" class="scrollLink">Scroll to link2 a> div> div id="textDiv"> p id="link1">strong>Anchor 1 strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea. p> p id="link2">strong>Anchor 2 strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas. p> div> script> $(document).ready(function( ) < $('a[href^="#"]').click(function( ) < $('html, body').animate(< scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top >, 500); return false; >); >); script> body> html>

To increase the performance, you can cache the $(‘html, body’) selector, so that it doesn’t run every time the anchor link is clicked:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> style> #textDiv < height: 1500px; > p < margin-top: 100px; height: 500px; > style> head> body> div id='linkDiv'> a href="#link1" class="scrollLink">Scroll to link1 a> a href="#link2" class="scrollLink">Scroll to link2 a> div> div id="textDiv"> p id="link1">strong>Anchor 1 strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea. p> p id="link2">strong>Anchor 2 strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas. p> div> script> let $root = $('html, body'); $(document).ready(function( ) < $(a.scrollLink).click(function( ) < $root.animate(< scrollTop: $($.attr(this, 'href')).offset().top >, 500); return false; >); >); script> body> html>

To update the URL, do it within the animate callback:

html> html> head> title>Title of the Document title> script src="https://code.jquery.com/jquery-3.5.0.min.js"> script> style> #textDiv < height: 1500px; > p < margin-top: 100px; height: 500px; > style> head> body> div id='linkDiv'> a href="#link1" class="scrollLink">Scroll to link1 a> a href="#link2" class="scrollLink">Scroll to link2 a> div> div id="textDiv"> p id="link1">strong>Anchor 1 strong> - Lorem ipsum dolor sit amet, nonumes voluptatum mel ea. p> p id="link2">strong>Anchor 2 strong> - Ex ignota epicurei quo, his ex doctus delenit fabellas. p> div> script> let $root = $('html, body'); $('a[href^="#"]').click(function( ) < let href = $.attr(this, 'href'); $root.animate(< scrollTop: $(href).offset().top >, 500, function( ) < window.location.hash = href; >); return false; >); script> body> html>

The hash property is used to set or return the anchor part of the href attribute value. The scrollTop() method is animated by enclosing it within the animate() method and defining the duration of the animation in milliseconds. The larger value, the slower the animation.

Читайте также:  Python распечатать значение переменной

Источник

Плавный скролл по странице к нужному ID (Scroll to id)

Очень популярная функция на различных одностраничниках — плавный скролл к нужному элементу на этой же странице. Чаще всего используется при навигации по меню. Если использовать обычные якоря без js, то плавного скролла не будет.

Самый простой скрипт для плавного скроллинга к нужному элементу.

Используется jQuery, поэтому нужно подключить https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js

Самый простой пример HTML:

$('a[href*="#"]').on('click', function (e) < e.preventDefault(); $('html, body').animate(< scrollTop: $($(this).attr('href')).offset().top >, 500, 'linear'); >);

Пример простой и удобный, но есть у него минус — при скроллинге не отмечаются активные пункты меню, если вам это и не надо, то можно без проблем использовать этот код. Если же нужно, чтобы при прокрутке активный блок выделялся в меню, тогда лучше использовать скрипт PageScroll2id, подробнее в этой статье Плавный скроллинг по странице к нужному элементу с использованием плагина PageScroll2id.

Использование @keyframes с препроцессором SASS. Базовый пример использования @keyframes в SASS: Создаем миксин, чтобы добавить…

CSS счетчики, в своей сущности, переменные CSS, значения которых могут быть инкрементированы при помощи CSS…

В одной из статей я приводил пример, валидации формы с помощью CSS, но с ограниченными…

Недавно применял на сайте интересную анимацию, выглядит она как гифка, но по факту это одна…

Источник

Have you ever gone to a website to read about something, but the website has so much information that you wish you had a place to click and skip all of its content to the specific information you are interested in, or either navigate from top to bottom without scrolling the sidebar scrollbar, just like the “Table of Contents” section we have above?

An anchor link is an answer to your problem. It will make it so easy and fast for you to narrow down to what you need rather than scrolling through all of it and sometimes down and up several times because you don’t know exactly where the blogger placed it. In this article, let’s have a deep understanding of adding anchor links to scroll to a specific page section.

You can view an anchor link from two perspectives: First, it is a hyperlink that you click to skip to a section of a document or a new page or website. Hyperlinks help the user to navigate between the webpage, websites by clicking on words, phrases, or even images.

It could be a sentence or a word in the middle of a blog, web pages, files, email addresses, locations on the same page, or anything else like a URL can address.

Second, as a table of content that looks like those in books but one that is clickable in that you don’t have to look for the page, it automatically takes you to the very content. Let’s call it an interactive table of content. The anchor tag element achieves all this.

The ‘href’ is a critical attribute in this anchor link since it indicates where the link will land. The ‘Text Displayed’ is visible to the reader, what the reader clicks on to move to the destination.

This is because once a reader clicks on the link text, they are directed to the specified location using the URL address.

Breakdown of the anchor tag element

Anchor links colors

  • By default, the links are interpreted as shown below by the web browsers.
  • For any un-visited link, it’s always underlined and blue in color
  • For a visited link its always underlined and purple in color
  • For any active link, it’s always underlined and red in color
    #visited #unvisited < color: purple;>#active Visited 
Unvisited
active

From the above example, we have directly defined the link colors to have a view of how they look. Below is the default CSS code that the browsers automatically execute when it meets the visited, un-visited or active link.

a:link, a:visited < color: (internal value); text-decoration: underline; cursor: auto; >a:link:active, a:visited:active

The target attribute helps to specify where you need to open the anchor link. By default, the target is normally set to the current browser window. But we can also play around with this and specify the target we need. These attributes include:

_self
– This tells the browser to open the link on the same window it was clicked on.
_blank– This tells the browser to open the link in a new window
_parent– This tells the browser to open the link in a new window
_top– This tells the browser to open the link in the full body of the document
Example:

     

Click any of the following links to see what happens

0pens in New
Opens in Self
Opens in Parent
Opens in Body

This can be achieved in three ways. With the anchor link, you can scroll from the top to bottom of the page just by a click; you can also scroll to the section of the page. Let’s look at the three different ways to achieve this.

Using the #bottom

Using the #bottom in the anchor tag will help you navigate from the top of the page to the bottom with just a click on the anchor text. That means you do not need to scroll through the page yourself.

Using the #top

The #top helps you navigate from the bottom of the page to the top of the page. You will only need to add the #top in the anchor tag, as shown below.

The worry with the two methods is that soon, it might not work in some browsers due to improvement in the HTML version. I would therefore recommend you using the next method we will look at, i.e., the Id selector.

Источник

Оцените статью