【JavaScript】スクロール位置を取得してクラスを付与したい(classList)
Q&A
Closed
解決したいこと
JavaScriptの勉強をしている初心者です。
スクロール位置を取得してクラスを付与したいのですが実装中にエラーが発生しました。
エラー内容を検索をしたのですが、解決方法をまだ見つけられておりません。
初歩的なミスかもしれませんが、ご教示いただけますと幸いです。
発生している問題・エラー
Uncaught TypeError: Cannot read properties of null (reading 'classList')
該当するソースコード
<header id="header">
<div class="header_in">
<h1>
<a href="#"><img src="images/top-header-logo.png" alt="ロゴ画像"></a>
</h1>
<nav>
<ul>
<li>お部屋</li>
<li>お料理</li>
<li>温泉</li>
</ul>
</nav>
<div class="header_btn">
<button type="button">宿泊予約</button>
</div>
</div>
</header>
header{
width: 100%;
position: fixed;
z-index: 100;
top: 0;
}
header.scroll_{
background-color: #fff;
height: 80px;
}
window.onscroll = scroll;
function scroll(){
scroll_position = window.pageYOffset;
console.log( scroll_position );
if(scroll_position >= 150){
document.getElementById('header').classList.add('scroll_');
}else{
document.getElementById('header').classList.remove('scroll_');
};
}
自分で試したこと
検証ツールのコンソールでIf文の部分だけ実装するとクラスの付与は行われたので
そもそもの書き方になにかミスがあるのかなとも思っています。
エラー内容にある「classList」がNULL?というのがよくわかりませんでした。
【追記】解決しました
「@_y_s」さんにご教示いただいた方法「
0 likes