Skip to content

Instantly share code, notes, and snippets.

@michimani
Last active March 2, 2018 00:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save michimani/15052ee0914a6c52561abad7560e7151 to your computer and use it in GitHub Desktop.
Save michimani/15052ee0914a6c52561abad7560e7151 to your computer and use it in GitHub Desktop.
Smooth movement from the table of contents in the Hatena blog article to the heading using jQuery.
$(document).ready(function(){
// 見出しタグにclass追加
$(".entry-content h1").addClass("content-h");
$(".entry-content h2").addClass("content-h");
$(".entry-content h3").addClass("content-h");
$(".entry-content h4").addClass("content-h");
$(".entry-content h5").addClass("content-h");
// 「目次」表示
$(".table-of-contents").before('<div class="contents-table"></div>');
$("<h3>目次</h3>").appendTo(".contents-table");
// 目次リストをdiv内に移動・リンク削除・class追加
$(".table-of-contents").appendTo(".contents-table");
$(".table-of-contents li a").removeAttr("href");
$(".table-of-contents li").addClass("ct-list-item");
// 各見出しの後ろに目次に戻るアイコン追加
var backToCt = "<div class='back-to-ct'><i class='blogicon-chevron-up'></i></div>";
var $cth = $(".content-h");
$(".content-h").append(backToCt);
// 目次クリック時
$(".ct-list-item a").click(function(){
var idx = $(".ct-list-item a").index(this);
var rect = $cth[idx].getBoundingClientRect();
var position = rect.top + window.pageYOffset - 45;
scrollToPosition(position);
});
// 目次へ戻る
$(".back-to-ct").click(function(){
var $cth = $(".table-of-contents");
var position = 45;
if ($cth.length > 0) {
var rect = $cth[0].getBoundingClientRect();
position = rect.top + window.pageYOffset - 45;
}
scrollToPosition(position);
});
function scrollToPosition(position) {
$("html,body").animate({
scrollTop : position
}, {
queue : false
});
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment