@onigiri15

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

【JavaScript】スクロール位置を取得してクラスを付与したい(classList)

解決したいこと

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

1Answer

エラーの内容はdocument.getElementById('header')がnullということだと思います。何が原因かは分かりませんが、可能性としては<header id="header">を読み込む前にscroll()関数が実行されていることが考えられます。対策としては</body>直前に<script>を書くことでしょうか。(すでにされている場合はご容赦ください。)

1Like

Comments

  1. @onigiri15

    Questioner

    回答いただきありがとうございます!
    記述いただいた対策を行ったところ、解決いたしました!
    ありがとうございます!

Your answer might help someone💌