0
votes

Because of the admin bar that shows for logged in users on my Wordpress site, hash links don't work as I'd like them to, i.e. they work as they should, but the top of the hash div is obscured by the Wordpress admin bar. So I am wondering if there is a way that, for logged in users, the position of all hashes can be offset by 28px, so that they show up correctly.

Presumably, if there is a script that can do this I will need to add it to my functions.php file and wrap it in:

if (is_user_logged_in()) :

[script here]

endif;
1
I suspect you'd want to change your CSS so that the div your 'hash links' are in moves down when the admin bar is there. Nothing fancy, just position it relatively - Nanne
What I am hoping for is a script that somehow automatically offsets the position of DIVs if there is a hash in the URL. - Nick
But why? Positioning your DIV in the correct way would be preferable to that, wouldn't it? That way, if for some reason there is another bar spawning, you get the same great results for free! - Nanne
@Nanne. Sorry, I don't really understand the solution you are suggesting. The admin bar essentially moves all of the content of the page down by 28px. This is fine. I don't want to reposition anything on the page, just adjust the position that the page scrolls/jumps to when there's a hash in the URL. Perhaps you'd like to post an answer with a bit more detail so that I can get my head around your suggestion? - Nick
AH, now I understand your question, it isn't really clear to my in it's current form. As I understood it before you wanted the div to be moved, but you just want the anchor's "fragment identifier" (that's what they're called as far as I know) to scroll lower because the offset breaks it in it's current form. - Nanne

1 Answers

1
votes

You'll actually want to do this in JavaScript. I'm assuming you have jQuery running. You can use the following code. This will run it all the time:

jQuery(document).ready(function(){

    jQuery(window).bind("hashchange", function() {
        jQuery("html,body").scrollTop(jQuery(window).scrollTop() - 28);
    });

});​

If you only want it to run when logged in, you can echo from your template with the PHP you suggested, with something along the lines of (not tested):

if (is_user_logged_in()) :

echo '<script>jQuery(document).ready(function(){

        jQuery(window).bind("hashchange", function() {
            jQuery("html,body").scrollTop(jQuery(window).scrollTop() - 28);
        });

      });​</script>';

endif;

Working example: http://jsfiddle.net/smUr4/

Thomas