Created
February 23, 2012 13:11
-
-
Save tzi/1892731 to your computer and use it in GitHub Desktop.
A #javascript #bookmarklet : Find the nearest anchor from your click
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
(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