오늘은 navbar 메뉴를 클릭하면 해당 내용이 있는 페이지로 스크롤하는 방법을 공부했다.
The Document
method querySelector()
returns the first Element
within the document that matches the specified selector, or group of selectors. If no matches are found, null
is returned.
The read-only target
property of the Event
interface is a reference to the object onto which the event was dispatched. It is different from Event.currentTarget
when the event handler is called during the bubbling or capturing phase of the event.
event.target
property can be used in order to implement event delegationThe dataset
read-only property of the HTMLElement
interface provides read/write access to custom data attributes (data-*
) on elements. It exposes a map of strings (DOMStringMap
) with an entry for each data-*
attribute.
data-*
attribute and its corresponding DOM dataset.property
modify their shared name according to where they are read or written:data-
. It can contain only letters, numbers, dashes (-
), periods (.
), colons (:
), and underscores (_
). Any ASCII capital letters (A
to Z
) are converted to lowercase.data-
prefix, and removes single dashes (-
) for when to capitalize the property's "camelCased" name.The Element
interface's scrollIntoView()
method scrolls the element's parent container such that the element on which scrollIntoView()
is called is visible to the user.
alignToTop
Optional
true
, the top of the element will be aligned to the top of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "start", inline: "nearest"}
. This is the default value.false
, the bottom of the element will be aligned to the bottom of the visible area of the scrollable ancestor. Corresponds to scrollIntoViewOptions: {block: "end", inline: "nearest"}
.behavior
OptionalDefines the transition animation.
auto
or smooth
.auto
.block
OptionalDefines vertical alignment.
start
, center
, end
, or nearest
.start
.inline
OptionalDefines horizontal alignment.
start
, center
, end
, or nearest
.nearest
.<div class="navbar__menu">
<ul class="navbar__menu">
<li class="navbar__menu__item active" data-link="#home">Home</li>
</ul>
</div>
const navbarMenu = document.querySelector('.navbar__menu');
navbarMenu.addEventListener('click', (event) => {
const target = event.target;
const link = target.dataset.link;
if (link == null) {
return;
}
console.log(event.target.dataset.link);
const scrollTo = document.querySelector(link);
scrollTo.scrollIntoView({behavior: 'smooth'});
});