0
votes

I've setup my site to scroll past a mandatory header element by using a scrollTop to a certain div function. I specifically set it to scroll slow so that the user "knows the header is up there" but on subsequent pages, I'd rather it just start at that scrolled position.

I'm trying to use a simple if / else statement to grab the wordpress page (is_home) and set the animation to 1200, else set the animation to 0. I've even gone in and setup a custom field on the page of is_home and True. But it's still not working. Any ideas how to fix the if / else or suggestions for a better way to implement this?

if (is_home()) {
    $(window).load(function () {
        $('html, body').animate({
            scrollTop: $("#grey").offset().top
        }, 1200);
    });
} else {
    $(window).load(function () {
        $('html, body').animate({
            scrollTop: $("#grey").offset().top
        }, 0);
    })
}
2

2 Answers

1
votes

Well, if(is_home()) is a php statement from the WordPress API, which isn't available in JS. You could include different script calls based on this, but it's rather bad practice in my opinion.

Make sure the below is executed after your plugin, and jquery obviously. Good place might be after wp_footer()

<?php 
if (is_home()) { ?>
    <script>
    $(window).load(function () {
        $('html, body').animate({
            scrollTop: $("#grey").offset().top
        }, 1200);
    });
    </script>    
<?php } else { ?>
    <script>
    $(window).load(function () {
        $('html, body').animate({
            scrollTop: $("#grey").offset().top
        }, 0);
    });
    </script>
<?php } ?>
0
votes

You are combining php and JavaScript together. is_home() is a PHP statement You need to rewrite your code as below:

<?php
    if (is_home()) {
 ?>
        <script type="text/javascript">
            $(window).load(function () {
                $('html, body').animate({
                    scrollTop: $("#grey").offset().top
                }, 1200);
            });
        </script>
<?php 
    } else {
?>
        <script type="text/javascript">
            $(window).load(function () {
                $('html, body').animate({
                    scrollTop: $("#grey").offset().top
                }, 0);
            });
        </script>        
<?php 
    } 
?>

Also use jQuery instead of $ to avoid conflict any other JavaScript libraries