• Hello everyone,

    I would not call myself a complete rookie in WP matters, but obviously my understanding of javascript lacks and the WP hook system lacks some major basics:

    I have a Twenty Eleven child theme and want to add one single piece of Javascript after the page is loaded:
    window.scrollBy(0,125);

    At least when I try it out in Firefox Javascript Environment it works. It is supposed to scroll the page a little after it is loaded.

    What I thought was necessary to achieve this goal is adding

    <?
    function ScrollOnLoad() { ?>
      <script type="text/javascript">
        window.scrollBy(0,125);
      </script>
    <?php }
    add_action('wp_head', 'ScrollOnLoad');
    ?>

    to my child functions.php. I also tried wp_loaded and after_setup_theme (with catastrophic results) as hooks.

    Well, it does nothing. Any ideas? At least it is in the head section of the code now, so technically this is a javascript question I suppose…

    Thank you all!
    Andreas

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter ditler

    (@ditler)

    OK, for now I solved it with a onLoad="javascript:window.scrollBy(0,125);" in the Body tag, and it works. Had tried that before but forgot the “javascript:” part.

    Nevertheless, I regularely stumble upon such problems so a hint what is wrong with the code above would be highly appreciated.

    Hi ditler,

    I believe the problem is that the code is being executed immediately upon browser load. You might want to tweak your javascript like so, that it does not execute until the page has fully loaded…

    <?php
    function ScrollOnLoad() { ?>
      <script type="text/javascript">
        jQuery(document).ready( function($) {
            window.scrollBy(0,125);
        });
      </script>
    <?php }
    add_action('wp_head', 'ScrollOnLoad');
    ?>

    The way you originally presented the code, the page might not have 125px to scroll by at the time the javascript is executed. So if you use a snipped like the one I provided above, OR you changed the WordPress Hook from wp_head to wp_footer … Either one should solve your problem.

    Does that help you?

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘One piece of javascript after the blog is loaded’ is closed to new replies.