-2

How can I make this code only work on the main page of a WordPress site?

jQuery(document).ready(function($) {
  var scrolled;
  window.onscroll = function() {
    scrolled = window.pageYOffset || document.documentElement.scrollTop;

    if (scrolled > 400) {
      $(".mega-menu-link").css({
        "color": "rgba(102,102,102,0.85)"
      })
    }

    if (400 > scrolled) {
      $(".mega-menu-link").css({
        "color": "rgba(255,255,255,0.8)"
      })
    }
  }
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • 3
    Only include it on the main page then? – Isaac Vidrine Mar 05 '19 at 19:16
  • provide more details, such as where is js code located, what you tried and etc – Samvel Aleqsanyan Mar 05 '19 at 19:25
  • Possible duplicate of [Run Specific Js on Specific page Wordpress](https://stackoverflow.com/questions/46019661/run-specific-js-on-specific-page-wordpress) or [WordPress load script only on homepage](https://stackoverflow.com/questions/27325811/wordpress-load-script-only-on-homepage-else-add-class). – showdev Mar 05 '19 at 19:31
  • Also see [Most efficient way to add javascript file to specific post and/or pages?](https://wordpress.stackexchange.com/questions/67802/most-efficient-way-to-add-javascript-file-to-specific-post-and-or-pages) and [Wordpress Enqueue for homepage only](https://wordpress.stackexchange.com/questions/23041/wordpress-enqueue-for-homepage-only-functions-php-wp-framework). – showdev Mar 05 '19 at 19:32

1 Answers1

0

One of the ways to include your script only on the main page is to put your code into the file and use if condition in the header or footer. Also you can include your code only into the main page as mented above.

<?php if(is_front_page()){?>
    <script src="your_script.js"></script>  
<?php } ?>
Dmitry S.
  • 1,544
  • 2
  • 13
  • 22