Determine cross-browser if an event or anchor element should be handled locally.
npm install local-links --save
Browsers have quirks. Knowing if a link is local should be easy, since we just want to know if the hosts are the same. But this can be difficult because of the aforementioned browser quirks. A few of them:
:80to the host of an anchor, but not the window
Because of that and a few other things I was doing all the time, such as finding the closest anchor to an element based on an event object, I decided it would be a good module (that at least I would use all the time).
var local = ;// `pathname()` will return the pathname as a string// if the link is local, otherwise it will return nulllocalpathnamedocument // '/page2'localpathnamedocument // nulllocalpathnamedocument // null// `hash()` will return the hash as a string// if the hash is to this page, otherwise it will return nulllocalhashdocument // nulllocalhashdocument // '#hash'localhashdocument // null
Returns the pathname if it is a non-hash local link, or null if it is not.
Always includes the leading
Returns the hash if it is an in-page hash link, or null if it is not. Always
includes the leading
Returns true/false depending on if the anchor pathname is equal to the
(which defaults to
Returns the pathname (or hash if
lookForHash is true) for local links, or null
if it is not. This is used by
hash() under the hood. The main
difference here is that you need to specify the
anchor yourself, and
anchor wont be looked up from
event.target like it would from the other methods.
The above methods will accept an
Event object, like the one you get from
click event handlers, or any
HTMLElement. You can also supply an
and a different
HTMLElement as the second parameter and it will take precedence.
If only an
Event object is supplied, the
HTMLElement will be found from
In the case that any
HTMLElement your provide is not an anchor
element, the module will look up
parentNodes until an anchor is found.
Event object is supplied, all methods will return
null if any of the following
shiftKey. This is because you almost always
want to treat modified click events as external page clicks.
If the anchor has target="_blank" it will return
null for both the
pathname method will return null for hash links that do not point
to a different page. To get the hash for one of these links use the
npm start and open
http://localhost:3000 to run the tests in your browser.
To run the tests in the cli, just run