Created
September 19, 2015 16:38
-
-
Save ThomasR/852326fb0aea403f5dcf to your computer and use it in GitHub Desktop.
A bookmarklet that shows named anchors / element ids for easy holinking
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
javascript: void (function { | |
var guid = 'anchor_detector'; | |
// save scroll pos | |
var hash = location.hash.replace(/^#/, ''); | |
var yTop = null; | |
if (/^[A-Za-z][-A-Za-z0-9_:.]*$/.test(hash)) { | |
var focusedElement = document.querySelector(`#${hash}, [name="${hash}"]`); | |
if (focusedElement) { | |
yTop = focusedElement.getBoundingClientRect().y; | |
} | |
} | |
if (document.querySelector('.' + guid)) { | |
[].forEach.call(document.querySelectorAll('.' + guid), function (el) { | |
el.parentNode.removeChild(el); | |
}); | |
} else { | |
var getCSSKeys = function () { | |
var result = []; | |
for (var key in getComputedStyle(document.body)) { | |
result.push(key.replace(/([A-Z])/g, function (x) { | |
return '-' + x.toLowerCase(); | |
})); | |
} | |
result.sort(); | |
return result.reduce(function (result, item) { | |
if (/^[0-9]/.test(item)) { | |
return result; | |
} | |
if (item !== result[result.length - 1]) { | |
result.push(item); | |
} | |
return result; | |
}, []); | |
}; | |
var forceInitial = getCSSKeys().map(function (key) { | |
return key + ': initial;'; | |
}).join('\n'); | |
var style = document.createElement('style'); | |
style.textContent = ` | |
body .${guid} { | |
${forceInitial} | |
border-radius: 3px; | |
background: -moz-linear-gradient(center top , dodgerblue 0%, royalblue 100%); | |
//border: 2px solid papayawhip; | |
display: inline-block; | |
box-shadow: 0 2px 5px 0 rgba(0, 0, 0, 0.16), 0 2px 10px 0 rgba(0, 0, 0, 0.12); | |
} | |
body .${guid} a { | |
${forceInitial} | |
display: inline-block; | |
padding: .1em .2em; | |
color: white; | |
font-family: Monaco,Menlo,Consolas,"Courier New",monospace; | |
font-size: inherit; | |
line-height: 1.25; | |
font-weight: bold; | |
text-shadow: 0px 1px blue; | |
cursor: pointer; | |
white-space: pre; | |
} | |
`.replace(/;/g, ' !important;'); | |
style.className = guid; | |
document.head.appendChild(style); | |
[].forEach.call(document.querySelectorAll('body [id], body [name]'), function (el) { | |
var anchor = el.id || el.name; | |
var span = document.createElement('span'); | |
span.className = guid; | |
span.innerHTML = `<a href="#${anchor}">#${anchor}</a>`; | |
el.insertBefore(span, el.firstChild); | |
}); | |
} | |
// restore scroll pos | |
if (typeof yTop == 'number') { | |
focusedElement.scrollIntoView(); | |
window.scrollBy(0, -yTop); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment