I found a tutorial online for a jQuery accordion:
The issue i am having is getting that to work within Wordpress. I have done everything in enque the script properly using wp_enqueue_script in the theme functions file. which I have done several times before but this just does not seem to be working. I added this script:
$(function($) {
var allAccordions = $('.accordion div.data');
var allAccordionItems = $('.accordion .accordion-item');
$('.accordion > .accordion-item').click(function() {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
});
to a separate .js file and enqued it but it will not work. correct me if I am wrong what I would have to do is create a initialization of that specific script as well. Could anyone assist me in doing so?
Thank you in advanced :)
3 Answers 3
You have to use jQuery instead of $ in Wordpress.
This is how you do it:
jQuery(function($) {
var allAccordions = $('.accordion div.data');
var allAccordionItems = $('.accordion .accordion-item');
$('.accordion > .accordion-item').click(function() {
if($(this).hasClass('open'))
{
$(this).removeClass('open');
$(this).next().slideUp("slow");
}
else
{
allAccordions.slideUp("slow");
allAccordionItems.removeClass('open');
$(this).addClass('open');
$(this).next().slideDown("slow");
return false;
}
});
});
Comments
Use jQuery(function($) ... instead of $(function($) ...
The $ is used elsewhere, so you need jQuery at the start of the DOM ready function. Then the $ keyword is passed into the function where you can safely use it inside.
Comments
Wordpress users $.noConflict() to refer to jQuery as jQuery. Your code is referring to it as $ but also passing the same as a function argument, so within the function you have overridden the $ global containing jQuery. This function is the same as jQuery(document).ready() and runs when the DOM is finished loading.
jQuery(function(){
var allAccordions = jQuery('.accordion div.data');
// etc... with jQuery known as jQuery
});
If you want to refer to jQuery as $ within your function, you can do so by using the following syntax to pass jQuery into your anonymous function arguments, where it is then know as $ in your function scope. This will run immediately and not wait for the DOM to load.
(function($) {
var allAccordions = $('.accordion div.data');
// etc... with jQuery known as $
})(jQuery);
If you want to refer to jQuery as $ but have it wait until the DOM loads, use jQuery.ready() or shorthand jQuery(callback).
jQuery(function(){
(function($) {
var allAccordions = $('.accordion div.data');
// etc... with jQuery known as $
})(jQuery);
});
jQuery(function($) ...instead of$(function($) ...