Files
buuh/lib/href.js
T

34 lines
1014 B
JavaScript
Raw Normal View History

2017-03-21 03:00:45 +01:00
var assert = require('assert')
module.exports = href
var noRoutingAttrName = 'data-no-routing'
// handle a click if is anchor tag with an href
// and url lives on the same domain. Replaces
// trailing '#' so empty links work as expected.
// (fn(str), obj?) -> undefined
function href (cb, root) {
assert.equal(typeof cb, 'function', 'sheet-router/href: cb must be a function')
window.onclick = function (e) {
if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return
var node = (function traverse (node) {
if (!node || node === root) return
if (node.localName !== 'a') return traverse(node.parentNode)
if (node.href === undefined) return traverse(node.parentNode)
if (window.location.host !== node.host) return traverse(node.parentNode)
return node
})(e.target)
if (!node) return
var isRoutingDisabled = node.hasAttribute(noRoutingAttrName)
if (isRoutingDisabled) return
e.preventDefault()
cb(node)
}
}