Skip to content

Commit

Permalink
jump to url hash
Browse files Browse the repository at this point in the history
  • Loading branch information
darylteo committed Jan 31, 2016
1 parent 8ea8ffa commit 4893a2a
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 1 deletion.
13 changes: 12 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,18 @@ Pjax.prototype = {
options.analytics()

// Scroll page to top on new page load
if (options.scrollTo !== false) {
// First parse url and check for hash to override scroll
var url = require('./lib/parse-url.js')(href)
if (url.hash) {
var name = url.hash.slice(1)
name = decodeURIComponent(name)

var target = document.getElementById(name) || document.getElementsByName(name)[0]
if(target) {
var offset = require('./lib/proto/offset.js')(target);
window.scrollTo(0, offset.top);
}
} else if (options.scrollTo !== false) {
if (options.scrollTo.length > 1) {
window.scrollTo(options.scrollTo[0], options.scrollTo[1])
}
Expand Down
5 changes: 5 additions & 0 deletions lib/parse-url.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
module.exports = function(url) {
var a = document.createElement("a")
a.href = url
return a
}
19 changes: 19 additions & 0 deletions lib/proto/offset.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// http://stackoverflow.com/questions/8111094/cross-browser-javascript-function-to-find-actual-position-of-an-element-in-page
module.exports = function(obj) {
var curleft = 0
var curtop = 0

if (obj && obj.offsetParent) {
do {
curleft += obj.offsetLeft
curtop += obj.offsetTop

obj = obj.offsetParent
} while (obj)
}

return {
left: curleft,
top: curtop,
}
}

0 comments on commit 4893a2a

Please sign in to comment.