Custom Javascript only works on homepage

I am using custom javascript to show and hide a bottom header element when the user scrolls and it only seems to be working on my homepage. If I go into the customizer/theme options, and change the page that is displayed, it works on the page, but only while I am in the customizer/theme options view. When I go to the pages themselves, the element does not appear at all. This is the script:

var available;
var percentage_of_page;
var half_screen;
var height;

$(window).scroll(function (e) {
    available = $(document).height();
    percentage_of_page = 0.05;
    half_screen = available * percentage_of_page;
    height = $(window).scrollTop();
    if (height > half_screen) {
        $('.headercall').show(400);
    } else {
        $('.headercall').hide(400);
    }
});

What is strange is that on every page besides the homepage in the javascript console I get a:
Uncaught TypeError: $ is not a function

I don’t see how it works as a function on the homepage but nowhere else. Am I missing something?

I also made a simpler function:

$(window).scroll(function() {
    if ($(window).scrollTop() > 100) {
        $('.headercall').show(400);
    }
    else {
        $('.headercall').hide(400);
    }
});

I still have the same problem. It works on the homepage, but not on any other page.

In WordPress you can’t rely on using $ directly for jQuery.

Try wrapping your code like this:

jQuery(function($) {

// Your code here

});

This will let you use $ to access jQuery and also lets you trust that any jQuery plugins have already been loaded.

1 Like

I saw solutions like this online, but kept using them wrong. Thank you for such a simple explanation. I am very new to javascript and was just playing with things I would google. Cheers!

We are delighted to assist you with this.

Cheers!

This topic was automatically closed 10 days after the last reply. New replies are no longer allowed.