java script 메모

[javascript] localStorage

그나쓰 2023. 1. 6. 17:52

localStorage 를 이용해서

버튼을 누를때마다 스크롤 위치가 변하는 페이지를 만들어보쟙

 

html은  index1과 index2를 만들거다

<!--index1.html-->
<a href="./index1.html" onclick="findKey();">category</a>
<!--index2.html-->
<main>top banner</main>
<section class="sec01">section1</section>
<section class="sec02">section2</section>
<div class="content">content</div>
<form name="myForm">
    <input type="hidden" value="" name="key">
    <ul class="sub_cate">
        <li><button class="go">sub_category</button></li>
    </ul>
    <ul class="event_cate">
        <li><button class="go2">bottom</button></li>
    </ul>
</form>

index2 에는 sub category 버튼과 bottom 버튼이 있다.

각 버튼을 누르면 input[type="hidden"]의 값이 각 버튼의 클래스명(go, go2)로 변경이 된 후 submit을 시킨다.

submit을 시키면서 localStorage에 key를 생성하고 input[type="hidden"]이 갖게 된 값을 key의 값으로 넣어준다.

 

sub category 탭을 클릭하면 sub category 탭이 주소창 아래에 위치하고

bottom 탭을 클릭하면 bottom 탭이 주소창 아래에 위치하도록 스크롤 값을 입력할거다.

 

 

index1에서 링크이동해서 index2로 들어갔을때

localStorage에 key가 찍혀있다면, key 아이템을 지워서

페이지 이동시 스크롤은 최상단에 위치해 있게 할거다.

 

/* index2 의 js */
//vh값 구하기
function vh(v) {
    var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    return (v * h) / 100;
}

const key = window.localStorage.getItem('key');
if(key === 'go'){
    $(window).scrollTop(vh(50));
}
else if(key == 'go2'){
    $(window).scrollTop(vh(130));
}
console.log(key);

$('button').click(function(e){
    const keyName = e.target.className;
    $('input[name="key"]').attr('value', keyName);
    window.localStorage.setItem('key', keyName);
    $('form[name="myForm"]').submit();
})

이러면 index2에서의 localStorage를 사용한 스크롤 이동 완!

새로고침을 해도 key값은 남아있기에 스크롤이 고정되어 있다.

 

/* index1 의 js */
function findKey() {
    if (window.localStorage.key("key")) {
        window.localStorage.removeItem("key");
    }
}

index1의 링크를 이동할때 findKey()를 실행시켜서

index1의 링크를 통해 index2로 이동하면 

localStorage에 key가 있으면 key를 제거한다!

그래서 스크롤은 최상단에 위치한다!

 

머리 꽁꽁 싸메고 어떻게 해야하나 하다가

언니가 localStorage 쓰면 되지 않을까 ? 해서

해결방법이 번쩍 ! 굳잡 ~ 언니 고마워 ♥