
今回、Webページを作成するにあたって
スクロールの位置を表示するナビ(言葉で説明するの難しいので下のDEMO見てくださいw)を
作りたくてカタカタしてみたものの、
▶Uncaught TypeError: Cannot read property ‘top’ of undefined
というエラーが出て、なかなかうまくいきませんでした。
色々調べてみると、offset().topの記述が原因だったようで、
var targetContentsTop = $(targetContents).offset().top;
⬇️のように書き換えることで・・
if ($(targetContents).length) { var targetContentsTop = $(targetContents).offset().top; }
やっとナビ完成!
※以下のコードをコピペして使用する場合は、jQueryの読み込みをお忘れずに!
See the Pen スクロールの現在位置を表示 by とりとん (@darakerutoriton) on CodePen.
コピペ用コード
$(function() { //ナビ部分を指定 var currentNav = $('#current_nav li a'); var contentsArr = new Array(); for (var i = 0; i < currentNav.length; i++) { var targetContents = currentNav.eq(i).attr('href'); if(targetContents.charAt(0) == '#') { if ($(targetContents).length) { var targetContentsTop = $(targetContents).offset().top; } var targetContentsBottom = targetContentsTop + $(targetContents).outerHeight(true) - 1; contentsArr[i] = [targetContentsTop, targetContentsBottom] } }; function currentCheck() { var windowScrolltop = $(window).scrollTop(); for (var i = 0; i < contentsArr.length; i++) { if(contentsArr[i][0] <= windowScrolltop && contentsArr[i][1] >= windowScrolltop) { //位置に来たら付与されるクラス名 currentNav.removeClass('current'); currentNav.eq(i).addClass('current'); i == contentsArr.length; } }; } $(window).on('load scroll', function() { currentCheck(); }); currentNav.click(function() { $('html,body').animate({ scrollTop: $($(this).attr('href')).offset().top }, 300); return false; }) });
body{ margin: 0; } #current_nav{ position: fixed; top: 50px; right: 10px; list-style: none; text-align: right; } .sec_style{ height: 500px; padding: 30px; font-size: 30px; text-shadow: 3px 3px #acacac; } #Sec1{ background-color:rgba(255,192,203,0.5); } #Sec2{ background-color:rgba(255,230,179,0.5); } #Sec3{ background-color:rgba(174,209,160,0.5); } a{ font-size: 16px; color: #999; text-decoration: none; } .current{ font-size: 20px; color: #008b8b; }
<ul id="current_nav"> <li><a href="#Sec1">Section1</a></li> <li><a href="#Sec2">Section2</a></li> <li><a href="#Sec3">Section3</a></li> </ul> <section id="Sec1" class="sec_style">▼ Section1</section> <section id="Sec2" class="sec_style">▼ Section2</section> <section id="Sec3" class="sec_style">▼ Section3</section>
簡単な解説

.current { font-size: 20px; color: #008b8b; }
今回は.currentというクラスを付与したので、スクロール位置によって上記のスタイルが上書きされています。
$(function() { //ナビ部分を指定 var currentNav = $('#current_nav li a');
最初にナビ部分のHTMLを指定します。
今回は、#current_navというIDで括った中のliの中のaをナビ部分として指定しています。
currentNav.click(function() { $('html,body').animate({ scrollTop: $($(this).attr('href')).offset().top }, 300); return false; }) });
この部分は、ナビをクリックしたときのスムーズスクロールを記述しています!
まとめ

今回は単純にjQueryの記述方法が原因でしたが、エラーが出るとドキッとしますね^^;
同じようにエラーが出てうまくできない方は、今回紹介したコードを試してみてくださいね♪
当ブログは、コピペ用のコードを紹介していますが、直接のご依頼も受け付けています♪
こういうデザインにしたい!
試してみたけどできなかった・・
などの簡単な修正でしたらワンコインから受け付けていますので、TwitterのDMかお問い合わせフォームよりお気軽にご連絡ください^^

簡単なのでぜひやってみてください〜

最後まで読んでいただきありがとうございました!