I have a JavaScript code snippet that I’d like to add to my WordPress + WooCommerce website:
$(document).ready(function() {
$('.input-text').on('input', function() {
var valueLength = $(this).val().length;
if (valueLength > 0) {
$(this).closest('.form-row').addClass('display-floating-label');
} else {
$(this).closest('.form-row').removeClass('display-floating-label');
}
});
});
This JS adds a custom class to WooCommerce checkout fields if the field’s text input is not empty.
How do I add this JS to my website?
My theme, OceanWP, provides a place to add custom JS at Appearance > Customize > Custom CSS/JS but adding it in the Custom JS text box didn’t work.
I’ve also tried downloading a Header/Footer scripts plugin and adding it in the header but that didn’t work either.
I’ve also tried adding it to the functions.php file a bunch of different kind of ways but I had no luck there either.
Here’s a fully functioning example with the exact same HTML code as the WooCommerce checkout fields have: JSFiddle. It works fine in the Fiddle so the classes in the JS are correct and adding it to my website should work, but it doesn’t.
The only part I do not understand is the <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> in the HTML code. Do I need to add this anywhere in my website?
I’m stuck, any help would be greatly appreciated.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Using this link, you will find helpful notes as to how to add a script to your WordPress website.
The main idea is to use inbuilt WordPress functions to load your scripts. This is done via the wp_enqueue_script function. Following examples provided in the aforementioned link, you will be able to learn how to enqueue your scripts the safe and secure way!
NOTE: Don’t get confused with the different functions – wp_enqueue_style is used for loading custom CSS stylesheets, NOT JavaScript code.
function load_your_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() ); // Used for loading stylesheets
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/WHEREVER/YOUR/FILE/IS/example.js', array(), '1.0.0', true ); // Used for loading scripts
}
add_action( 'wp_enqueue_scripts', 'load_your_scripts' );
Please let me know if you run in to any issues with your code and I will be sure to help you along the way 🙂
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0