Solution:1
You need to add jQuery as a dependancy when enqueueing a jQuery script with wp_enqueue_script:
wp_enqueue_script( 'toggle-script', '/assets/js/accordiontoggle.js', array('jquery'), '1.0.0', true );
Typically a jQuery script must be wrapped with:
jQuery(function($) {
$(document).ready(function() {
// Your code goes here
});
});
Or (use this because you are manipulating images):
jQuery(function($) {
$(window).on('load', function () {
// Your code goes here
});
});
This is important because wp_enqueue_scripts
inserts the script into the document <head>
which is loaded first. Without waiting for document ready
or window load
event, you are selecting elements with jQuery that don’t exist yet.
From jQuery docs:
‘A page can’t be manipulated safely until the document is “ready.” jQuery detects this state of readiness for you. Code included inside $( document ).ready()
will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute. Code included inside $( window ).on( "load", function() { ... })
will run once the entire page (images or iframes), not just the DOM, is ready.’