Trying to Load jQuery

When enqueuing a script from a child theme, you have to use get_stylesheet_directory_uri rather than get_template_directory_uri(). The template directory is the parent theme, and the stylesheet directory is the one shared by the directory the active stylesheet is using.

In your functions.php file, the enqueuing would be:

function avtheme_scripts() {
    wp_enqueue_script( 'av-about-fade', get_stylesheet_directory_uri() . '/js/about-fade.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'avtheme_scripts' );

That will enqueue the script properly for you and make it available. Now looking at the error the console is giving for your actual jQuery – it says it can’t find the variable jquery. WordPress is looking for jQuery with the capital Q.

Here’s how you can put the script together so that you don’t have to replace every $ with jQuery when writing your scripts. The following block of code would go in your about-fade.js file.

(function( $ ) {
    'use strict';
    $( document ).ready( function() {
      if( $( '.fading-start1' ).length > 0 ) {
        setTimeout( function() {
            $( '.fading-start1' ).addClass( 'fading-finish1' );
        }, 3000 );
      }
    } );
    // Have never used beforeunload myself, so not sure how reliable it is.
    $( window ).on( 'beforeunload', function() {
      $( '.fading-start1' ).removeClass( 'fading-finish1' );
    } );
} )( jQuery );

One thing that used to bother me when I wrote a lot of jQuery was that I’d get console errors because the jQuery would try to execute on elements that weren’t there. For example, if I had and element like <div class="fading-start1"> on the home page, but nowhere else on the site, I’d see errors telling me that it couldn’t find `’. Well obviously, because it’s not there.

So what I generally do now is check to see if elements exist before I run any jQuery on them by checking for the element’s ‘length’ and if it’s greater than zero, jQuery will attempt to run something on it. If it’s length (quantity of elements with that selector) is less than 0, then it’s not there. (Length is a bit of a weird name for it, but that’s what it is.)

That one extra instruction spares my sanity quite a bit. 🙂

Addendum:

To use opacity with your CSS you just have to add that to the transitions:

.fading-start1 {
    background-color: #fff!important;
    opacity: 0.65; 
    transition: background-color 3s linear, opacity 3s linear!important;
    -moz-transition: background-color 3s linear, opacity 3s linear!important;
    -o-transition: background-color 3s linear, opacity 3s linear!important;
    -webkit-transition: background-color 3s linear, opacity 3s linear!important;
}