Question

I'm adopting @Old Pro's answer:

history.replaceState({}, '', window.location.href.substring(0, window.location.href.indexOf('#')))

My objectives are:

  1. To redirect from Page 1 to Page 2 and jump to anchor #DivTgt

  2. Once redirected, will remove #DivTgt from the URL. Therefore the URL will only display page2.php and not page2.php#DivTgt

@Old Pro's method works perfectly on Firefox but not on Chrome/Safari. For Chrome/Safari, it does redirect and #DivTgt removal but doesnt jump to anchor #DivTgt. @Old Pro's method is inserted on Page2 (target page).

I've tried both replaceState and pushState and both return a same result (ie only works on Firefox)

Did i miss anything.

Was it helpful?

Solution

First of all, I would suggest to move your JavaScript code into .ready() function. Otherwise your code may be called when DOM is not yet ready.

I can not tell you why it's not working, but apparently some problems are existing with new html5 push and replace state functions due to no clear specs. Please read: history.replaceState() example?

So to help you, I can propose a workaround. Keep your push/replace state function, and force scrolling to your anchor with javascript.

Can you have a look at my example please ? http://francoisjeunesse.be/example/page1.php

Page1.php:

<a href="page2.php#DivTgt">Go to Page 2</a>

Page2.php:

<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.0.min.js" ></script>
<script type="text/javascript"> 
$( document ).ready(function() {
    if (window.location.href.indexOf('#DivTgt') != -1){
        document.getElementById("DivTgt").scrollIntoView(true);
    }
    history.pushState({}, '', window.location.href.substring(0, window.location.href.indexOf('#')));

});
</script>
</head>
<body>
<div style="border:1px solid #000;min-height:1000px">spacer</div>
<a id="DivTgt" name="DivTgt"/>anchor is here</a>
</body>
</html>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top