mseifert
mseifert

Reputation: 5670

Scrolling to Anchor Tag with php dynamically created page

I have a page where entries are read from a table and then php generates the divs where each row is displayed - the div's name & id are set to a unique string based on the record #. For example:

When the page is loaded, it is passed the unique anchor string of the record to scroll to in the format: href='showpost.php#g50'

When the page loads it correctly shows the url with the anchor but it doesn't scroll.

However, if I put my cursor on the browser's address bar and press <Enter> the page scrolls correctly to the record. Oddly enough, <F5> and <Ctrl-R> will not work (Firefox 16).

I am guessing that the page being dynamically created has something to do with it. Any ideas what might be going on?

Upvotes: 3

Views: 6367

Answers (2)

Andriy Petrusha
Andriy Petrusha

Reputation: 129

Very useful example, thanks SISYN. But I have my version

let hashSplit = location.href.split('#');
let curHash = hashSplit[1];
if(typeof curHash !== 'undefined') {
    $('html, body').animate({
        scrollTop: $('#' + curHash).offset().top
    }, 1000);
}

Upvotes: 0

SISYN
SISYN

Reputation: 2259

You can always just use a simple javascript call to scroll to an anchor. You can call Javascript code from anywhere in the page, so to be safe, you could put it at the end of the page after the PHP has generated all the anchors.

<?php 
    // php generation code here
?>
<script type="text/javascript">
    var hashSplit = location.href.split('#');
    var curHash= hashSplit[1];
    window.location.hash = curHash;
</script>

Or if you already know what the anchor of the page is going to be via php you can do it even easier.

<?php
    $anchor = "home";
?>
<script type="text/javascript">
    window.location.hash = "<?= $anchor; ?>";
</script>

Upvotes: 1

Related Questions