Created
December 21, 2011 13:46
-
-
Save 66Ton99/1506109 to your computer and use it in GitHub Desktop.
Add hash(anchor) to url without scrolling
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
/** | |
* Add hash to url without scrolling | |
* | |
* @param String $url - it could be hash or url with hash | |
* | |
* @return void | |
*/ | |
function addHashToUrl($url) | |
{ | |
if ('' == $url || undefined == $url) { | |
$url = '_'; // it is empty hash because if put empty string here then browser will scroll to top of page | |
} | |
$hash = $url.replace(/^.*#/, ''); | |
var $fx, $node = jQuery('#' + $hash); | |
if ($node.length) { | |
$fx = jQuery('<div></div>') | |
.css({ | |
position:'absolute', | |
visibility:'hidden', | |
top: jQuery(window).scrollTop() + 'px' | |
}) | |
.attr('id', $hash) | |
.appendTo(document.body); | |
$node.attr('id', ''); | |
} | |
document.location.hash = $hash; | |
if ($node.length) { | |
$fx.remove(); | |
$node.attr('id', $hash); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It doesn't work in IE6