erwin erwin - 5 months ago 20
jQuery Question

wordpress ... toggle the new comment_form

I am trying to insert a link to toggle the comment_form using jQuery onclick, but it does not work ...

In my comments.php , I added the following html around the comment_form() :

<p>BEFORE FORM</p>
<a style="cursor:pointer" onclick="jQuery('#add-comment).toggle();">Toggle comment-form</a>
<div id="add-comment" style:"display:none;">

<?php $comments_args = array(
....
);
comment_form($comments_args);
?>

<p>AFTER FORM</p>
</div>


and to be sure jQuery is loaded, I added the following code in my functions.php

if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11);
function my_jquery_enqueue() {
wp_deregister_script('jquery');
wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.min.js", false, null);
wp_enqueue_script('jquery');
}


the link is correctly displayed but the form is not hidden and the toggle does not activate ..
where am I wrong ?

Answer

Two errors:

You are missing the closing quote:

<a style="cursor:pointer" onclick="jQuery('#add-comment').toggle();">Toggle comment-form</a>
                                                       ^-- here 

which results in a syntax error. Apart from that, you need a = instead of a ::

<div id="add-comment" style="display:none;">
                           ^- here

This is the reason why the form isn't hidden at the start.

With these two errors fixed it works:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>BEFORE FORM</p>
      <a style="cursor:pointer" onclick="jQuery('#add-comment').toggle();">Toggle comment-form</a>
      <div id="add-comment" style="display:none;">

        Comment form

      <p>AFTER FORM</p>       
      </div>

Comments