How to fix the error "TypeError: $ is not a function" in a custom WordPress page?

I created a custom WordPress page through a plugin where I want to enable / disable comments using this code

<script type="text/javascript"> $("comment_switch").click(function () { $("comments").toggleClass("hidden"); }); </script> 

I put it in the <body> . To generate the <head> , I used the standard WordPress function wp_head(); . When I check the source code of the page, I see in the main section <script src="http://10.1.1.6/wp-includes/js/jquery/jquery.js?ver=1.10.2" type="text/javascript"> which I thought would be sufficient to use jQuery.

Can someone help me make jQuery code? The entire source code of the page can be found here.

+7
jquery html wordpress
source share
3 answers

You are probably missing some class markup . and DOM ready functions

 jQuery(function($) { // DOM is now ready and jQuery $ alias sandboxed $(".comment_switch").click(function () { $(".comments").toggleClass("hidden"); }); }); 
+29
source share

you need to encapsulate a javascript function that executes in the DOM ready event

 <script type="text/javascript"> $(function () { $("comment_switch").click(function () { $("comments").toggleClass("hidden"); }); }); </script> 
-one
source share
  <script type="text/javascript"> (function () { // 1) remove the "$" $(".comment_switch").click(function () { // 2) add "." if this a class or "#" // if it is an id $(".comments").toggleClass("hidden"); }); }); </script> 
-one
source share

All Articles