I am creating several jQuery scripts to help validate forms before they are submitted. I have read that it is best to always separate jQuery scripts into a separate file so that you can load the script with wp_enqeue_script
.
However, if I am doing something like this:
jQuery(function()
{
var ButtonSelector = "#submit-button";
jQuery(document).on('click', ButtonSelector, function()
{
var ValidEntry = true;
ClearError('#venue_name');
var name = jQuery("#venue_name").val();
if (name == "")
{
CreateError("#venue_name", "Name is Required");
ValidEntry = false;
}
if (!ValidEntry)
{
jQuery('html, body').animate({scrollTop:0}, 'slow');
}
EnableButton(ButtonSelector);
return false;
});
});
Since this function is only used in the one individual form, would it still make sense to separate it out? If I did separate it, wouldn’t that mean that it would load for every single page?
You can target a specific page using
is_page()
when you are enqueueing your JS file.This way, you will conditionally enqueue your JS to that page only.
you could still put the script in a seperate js-file, but separate from the rest of your script(-files) too – and enqueue it conditionally, for example:
that would be in your
functions.php
, where you enqueue your scriptsWhen using
is_page()
I would also recommend doing so with an||
since the page title and page name (aka page slug) might change – if only by accident. You could also use the page ID but that too might not be consistent between development and production.For example:
Overkill? Perhaps. But it’s something to be aware of.