Skip to content

Instantly share code, notes, and snippets.

@beshur
Created November 24, 2014 22:17
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 beshur/3a66b643a176eb1495d0 to your computer and use it in GitHub Desktop.
Save beshur/3a66b643a176eb1495d0 to your computer and use it in GitHub Desktop.
jQuery wordpress j/k next/prev navigation
// Simple J/k navigation for Wordpress
// by Alex Buznik (@beshur)
//
// Change t value for the correct selectors of the items that need to be traversed
(function($) {
$(function() {
var is_blog = true;
if (!$("body").hasClass("blog")) {
is_blog = false;
}
$(window).on("keyup", function(e) {
if (e.which == 74 || e.which == 75) {
// forward
var dir = true;
// backward
if (e.which == 75) dir = false;
var t = $("article > h2, article img, article iframe");
if (is_blog) {
t = $("article.post, article + .pagination");
}
var scrollTop = $(window).scrollTop();
t.each(function(i) {
var o = $(this).offset().top;
if (o > scrollTop || o == scrollTop || i+1 == t.length) {
var to = o;
if (o == scrollTop && dir) {
to = $(t[i+1]).offset().top;
} else if (o == scrollTop && !dir) {
if (i == 0) return false;
to = $(t[i-1]).offset().top;
}
if (!dir) {
to = $(t[i-1]).offset().top;
if (o < scrollTop && i != 0) {
to = $(this).offset().top;
}
} else {
// if forward, post is last and position on last
if (i+1 == t.length) return false;
}
$("html,body").stop(true, true).animate({
scrollTop: to
}, "fast");
return false;
}
});
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment