Skip to content Skip to sidebar Skip to footer

Wordpress Load Script Only On Homepage, Else Add Class

Not really sure how to achieve what I am trying to do here, hopefully you guys can help. I have a script within my function.js file which makes my fixed header fade into view when

Solution 1:

You can add a class to the body in your home page. And layout the .bg with fixed position as you want for that other pages:

<body class="home">

:not(.home) .bg{position:fixed;}

Solution 2:

if ( is_home() || is_front_page() ) { 
    wp_enqueue_script($scriptUrl);
} else { 
    add_filter("body_class" , function($classes){
        $classes[] = "added-class";
        return$classes;
    }); 
} 

If it's home, enqueue some script (should be done before wp_enqueue_scripts action. Else it will add some classes to body. Remember tho that you need to make proper body tag

<body <php body_class(); ?>>

Solution 3:

Ok, here's my solution:

I created a JS script:

(function ($) {
  $('#navbar').addClass('show');
}(jQuery));

Then I tweaked the if/else posted earlier:

<?php if ( is_home() || is_front_page() ) { wp_enqueue_script('header-fade', get_template_directory_uri() . '/js/header-fade.js'); } else { wp_enqueue_script('opaque', get_template_directory_uri() . '/js/opaque.js'); }; ?>

So, if it's the front page (home), the fade on scroll script fires. If it's any other page, the opaque script fires instead which makes the navbar visible on page load.

Done and done. :)

Post a Comment for "Wordpress Load Script Only On Homepage, Else Add Class"