Notice
Recent Posts
Recent Comments
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | ||||
4 | 5 | 6 | 7 | 8 | 9 | 10 |
11 | 12 | 13 | 14 | 15 | 16 | 17 |
18 | 19 | 20 | 21 | 22 | 23 | 24 |
25 | 26 | 27 | 28 | 29 | 30 | 31 |
Tags
- 이벤트 위임
- slice
- array
- 이벤트 루프
- object
- Flex
- 스크롤
- 클로저
- ajax
- 배열
- ES6
- 비동기
- input
- scroll
- Promise
- video
- map
- dom
- Push
- event
- json
- ios
- 이벤트
- This
- 애니메이션
- 모듈
- 문자열
- animation
- IntersectionObserver
- 객체
Archives
- Today
- Total
FEDev Story
페이지내 hash 이동하기 본문
브라우저 주소창에 hash값을 id로 페이지내에서 이동해야 할 경우가 있다.
http://www.test.co.kr/list/list.html#d_20200330
window.location.hash로 hash값을 얻을 수 있다.
var hash = window.location.hash; //#d_20200330
아래는 window.location.hash로 얻은 hash값을 moveToHash()함수에 전달하여 호출함으로써 페이지내에서 해당 hash값을 id로 하는 div로 이동하는 코드이다.
var hash = window.location.hash;
function moveToHash(hash){
if(hash.length > 0){
var selector = document.querySelector(hash);
$('.acc_head a', $(selector)).trigger('click'); //click이벤트를 트리거해야 할 경우
setTimeout(function(){
$(window).scrollTop($(selector).offset().top);
}, 300)
}
}
moveToHash(hash);
$(window).bind('hashchange', function(){
var hash = window.location.hash;
moveToHash(hash);
});
페이지가로드되고 URL에 # ...을 추가하면 moveToHash 함수가 실행되지 않으므로 해당 id로 이동하지 않는다.
대신 hashchange 이벤트를 사용할 수 있다. 이렇게하면 해시가 변경 될 때마다 moveToHash 함수를 실행하여 해당 id로 이동할 수 있다.
관련문서:
https://stackoverflow.com/questions/6857982/location-hash-problems-when-manually-entering-url-script-is-not-run
location.hash problems when manually entering url, script is not run
I'm trying to make it possible to reach certain tabs in the page by using hash-variables. It works as intended for: Links within the page Opening a new browser window/tab with the adress (test.ph...
stackoverflow.com
'Web.Dev' 카테고리의 다른 글
특정 엘리먼트로 스크롤을 천천히 이동시키기. scrollIntoView() (0) | 2021.08.27 |
---|---|
스크롤 체이닝 현상 막는 법 (0) | 2021.08.26 |
Android / IOS 데스크탑에서 모바일기기 디버깅하기 (0) | 2020.03.17 |
input readonly focus 제거 (0) | 2020.01.22 |
javascript:void(0)과 #중에 어떤것을 사용할까 (0) | 2019.12.05 |
Comments