Skip to content

Instantly share code, notes, and snippets.

@tzi
Created February 23, 2012 13:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tzi/1892731 to your computer and use it in GitHub Desktop.
Save tzi/1892731 to your computer and use it in GitHub Desktop.
A #javascript #bookmarklet : Find the nearest anchor from your click
(function() {
// Attributes
var reg = new RegExp( '" id="([^"]*)"', 'g' ),
popin = new bm_popin( 1892731 );
popin.title( 'myAnchor' );
popin.text( 'Click on your page' );
// Recursive function
function get_previous_node_id( node, parse ) {
if ( node.id ) {
return '#' + node.id;
}
if ( node.name ) {
return '#' + node.name;
}
if ( parse ) {
var exec = reg.exec( node.innerHTML );
if ( exec != null && exec.length > 1 ) {
return '#' + exec[ 1 ];
}
}
if ( node.previousSibling != null ) {
return get_previous_node_id( node.previousSibling, true );
}
if ( node.parentNode != null ) {
return get_previous_node_id( node.parentNode, false );
}
return '#';
}
// Event handler
document.body.onclick = function( event ) {
var anchor = get_previous_node_id( event.target );
popin.text( 'The anchor is: \n' + anchor );
window.location.hash = anchor;
document.body.onclick = null;
return false;
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment