jQuery and WP custom theme is not working
-
Hi,
I’m trying to use the jQuery code I found on CodePen on my project but all methods I’ trying are not working.
I’m using @wordpress/scripts to bundle all my files. And all java script is loaded as a modules.This is my folders hierarchy:
--build --css |--base |--modules |--style.scss --img --src |--modules | |--Accordion.js | |--StickyHeaders.js |--index.js --template-parts --functions.php --package.json --webpack.config.js --all-pages.php
My code is inside Accordion.js file and looks like this:
import $ from 'jquery'; var headers = ["H1","H2","H3","H4","H5","H6"]; $(".accordion").click(function(e) { var target = e.target, name = target.nodeName.toUpperCase(); if($.inArray(name,headers) > -1) { var subItem = $(target).next(); //slideUp all elements (except target) at current depth or greater var depth = $(subItem).parents().length; var allAtDepth = $(".accordion p, .accordion div").filter(function() { if($(this).parents().length >= depth && this !== subItem.get(0)) { return true; } }); $(allAtDepth).slideUp("fast"); //slideToggle target content and adjust bottom border if necessary subItem.slideToggle("fast",function() { $(".accordion :visible:last").css("border-radius","0 0 10px 10px"); }); $(target).css({"border-bottom-right-radius":"0", "border-bottom-left-radius":"0"}); } });
At my main JS file which is
index.js
I’m importing this file like below:
import Accordion from './modules/Accordion'
But the code is not working. I tried to wrap it within the function like below but also no luck:
import $ from 'jquery'; $(document).ready(function() { var headers = ["H1","H2","H3","H4","H5","H6"]; $(".accordion").click(function(e) { var target = e.target, name = target.nodeName.toUpperCase(); if($.inArray(name,headers) > -1) { var subItem = $(target).next(); //slideUp all elements (except target) at current depth or greater var depth = $(subItem).parents().length; var allAtDepth = $(".accordion p, .accordion div").filter(function() { if($(this).parents().length >= depth && this !== subItem.get(0)) { return true; } }); $(allAtDepth).slideUp("fast"); //slideToggle target content and adjust bottom border if necessary subItem.slideToggle("fast",function() { $(".accordion :visible:last").css("border-radius","0 0 10px 10px"); }); $(target).css({"border-bottom-right-radius":"0", "border-bottom-left-radius":"0"}); } }); });
I’ve to also tried to import jQuery library inside my .php file within <script> tags like below but that is not changing anything:
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
I don’t know jQuery so hope someone can help me here.
- The topic ‘jQuery and WP custom theme is not working’ is closed to new replies.