Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Ignore links with specific data attribute in href() listener #27

Merged
merged 3 commits into from
Aug 18, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@ router('/multiply', 4)
// => 8
router('/divide', 8)
// => 4

You can ignore specific links that you do not want to process through routing by adding the `data-no-routing` attribute.

```html
<a href="/my-external-link" data-no-routing>Non routed link</a>
<a href="/another-external-link" data-no-routing="true">Not routed either</a>
```

### virtual-dom example
Expand Down
7 changes: 7 additions & 0 deletions href.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ const assert = require('assert')

module.exports = href

const 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.
Expand All @@ -11,6 +13,8 @@ function href (cb) {
assert.equal(typeof cb, 'function', 'cb must be a function')

window.onclick = function (e) {
if ((e.button && e.button !== 0) || e.ctrlKey || e.metaKey || e.altKey || e.shiftKey) return

const node = (function traverse (node) {
if (!node) return
if (node.localName !== 'a') return traverse(node.parentNode)
Expand All @@ -21,6 +25,9 @@ function href (cb) {

if (!node) return

const isRoutingDisabled = node.hasAttribute(noRoutingAttrName)
if (isRoutingDisabled) return

e.preventDefault()
const href = node.href.replace(/#$/, '')
cb(href)
Expand Down