Wordpress Tutorial: Prevent Page from jumping to top on Reload

Big web page headers are in design vogue at the moment, so I thought I’d incorporate one into my new site, keeping all links and content below the fold. After I’d dropped the header into the template, I ran into an annoying problem: every time a user clicked a link, the view would bounce back to the top of the page as it reloaded, forcing the user to scroll all the way back down to the content area.
That might seem like an inconsequential problem, but the Herculean amount of mouse action involved discouraged users from browsing more than a page or two. I wanted a simple php-based solution, and I eventually found it on the WordPress forums courtesy of member gelo.tv.
Below, you’ll find a slightly-modified version of the gelo.tv’s original code, and the instructions to implement it. Using simple HTML page anchors and a bit of basic scripting, this code first checks to see whether or not the user has loaded the home page (where we want them to look at the header), and then checks to see whether or not there’s already an anchor hash tag in the URL.
If not, the code will add an anchor tag into the URL, forcing the page view down to a name= anchor set by you.
Step 1: Open your index.php template file, and delete the <body> tag
Step 2: Using page anchors, set the location that you want the page to align with
Anchors create links to a location within the current page. Typically, anchors are used to link to a graphic or paragraph half-way down a long web page.
What we want to do here is decide where in the index.php file to drop our anchor. My anchor is set at the very top of my content div, so whenever a user clicks a link, the page reloads, showing the content aligned to the top of the browser window, and skipping the header.
Anchors are set as a parameter of any other tag. To add a page anchor, add name="youranchorname" to the div tag that begins your content section. For example:
BEFORE: <div id="contentstart">
AFTER: <div id="contentstart" name="anyanchorname">
It doesn’t matter what the name of the anchor is.
Step 3: Insert the following php snippet into your index.php file, right where the body tag used to be.
<?php
global $anchor_var;
$Url="Http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
$mystring = '#';
$pos = strpos($mystring, $Url);
if (($pos === false) && (is_front_page() )) {
$anchor_var = false;
} else {
$anchor_var = true;
}
?>
<?php if ($anchor_var) : ?>
<body onload="location='#YOURANCHORNAME'">
<?php else : ?>
<body>
<?php endif; ?>
Don’t forget to replace “YOURANCHORNAME” with the name of your anchor from step 2.
And that’s it. The original code featured an is_home() instead of an is_front_page(), but I found that this caused the script to stop working when I associated a specific page to be the home page in the WordPress back end.



