Search code examples
javascriptjquerylessrace-condition

On Page Load Offset Value set to 0. On Inspection value is calculated


The goal is to use a url fragid to jump to a particular section on a separate page on page load. <a href="page.php#section>

The unexpected behavior is that on page load the offsetTop does not seem to get calculated or the value gets overwritten.

  • When I call console.log($("#section").offset());
  • from a <script> tag of the loaded PHP file,
  • or a linked js file calling at jQuery(document).ready(function() {}),
  • or $(window).on('load', function() {})

all result in a console log of { top: 0, left:0 }.

However once the file is loaded, I manually open Dev Tools and enter console.log($("#section").offset()); and it returns the expected output of { top:200px, left: 200px }. - When I load the page without calling the LESS file the calculation happens. This leads me to believe that it is a race condition with LESS. However this seems strange that LESS would be fighting and overwriting a html:5 function.


Solution

  • Append a simple URI query component to the value of the href attribute of your anchor.

    <a href="page.php?hash=section">Click here</a>
    

    Then, add code on page.php to handle the URI query in the GET request.

    <!-- at bottom of markup just before end body -->
    <?php if (@$_GET['hash'] === 'section') echo '<script>window.location.hash="section";</script>'; ?>
    </body>