Richard J Green

jQuery and WordPress No Conflict

Last night, I was doing some work on my blog as ever since I wrote the custom theme I use (and since updated it) I have neglected my mobile visitors and the mobile views not only looked awful but in some cases, depending on the device you were using made the content totally invisible due to the black wallpaper background and the black body text appearing on top of each other.

I decided I wanted to add a fixed top header that faded away as you scroll down the page and reappeared as you scroll back up as I’ve seen it on a number of sites before and the effect is both aesthetically pleasing and maximises the real estate on devices with small screens such as smartphones. I found a site which had a good reference on how to implement this using jQuery and I added the script to the site and the relevant CSS selectors but it wasn’t working.

Using the Developer Tools in Internet Explorer, I could see that my script file containing the jQuery was generating an error on line 1 with the error $ is not defined. Being that I’m just about good enough to write and tweak the jQuery for my needs, I had to resort to searching online to find the solution so I thought I would post it here in the hope that I help some other WordPress administrator out there struggling with the same issue.

The problem arises not because of a problem with jQuery but a nuance with WordPress and how it implements jQuery. With a normal site under normal conditions, you load the jQuery library to allow you to invoke jQuery on the site and in doing so, jQuery assign itself the $ symbol as a variable used for invoking jQuery. jQuery includes an optional mode called noConflict which helps to prevent conflicts with other libraries and extensions that may also use the dollar symbol as a variable. WordPress implements jQuery in no conflict mode and as a result, the dollar symbol is not available and instead, we have to invoke jQuery using the jQuery named variable.

When writing jQuery scripts for use on a WordPress site, we need to replace all instances of the dollar symbol with the jQuery notation. Below is an example line from the script I first wrote for the disappearing menu bar script referencing jQuery using the dollar symbol which causes the $ is not defined error.

    didScroll = true;

To make the script function properly on the WordPress site, I had to modify this section of code to replace $ with jQuery as shown below.

    didScroll = true;

After changing this and all the remaining references in the script and saving it back to the site, the Developer Tools ceased to report the error and the script started to function as expected.

Exit mobile version