Skip to content

Instantly share code, notes, and snippets.

@66Ton99
Created December 21, 2011 13:46
Show Gist options
  • Save 66Ton99/1506109 to your computer and use it in GitHub Desktop.
Save 66Ton99/1506109 to your computer and use it in GitHub Desktop.
Add hash(anchor) to url without scrolling
/**
* 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);
}
}
@66Ton99
Copy link
Author

66Ton99 commented Dec 21, 2011

It doesn't work in IE6

@samdavidson
Copy link

@66Ton99 LOL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment