Wordpress - How to limit length of comment

In this tutorial, I'll teach you how to limit the length of comment. In some places on the web, you have seen that there are limit for comments word i-e 140 characters. The code i will provide you be the mixture of php and jquery.
  1. jQuery(function($) {
  2. var input_comment = $( '#form textarea' );
  3. var submit = $( '#form .submit' );
  4. var comment_limit = 140;
  5. $( '<div class="limit_info"><span>' + comment_limit + '</span>  left</div>' ).insertAfter( input_comment);
  6. input_comment.bind( 'keyup', function() {
  7. var length_of_comment = $(this).val().length;
  8.  var left = comment_limit - length_of_comment;
  9.  $( '.limit_info span' ).html( left );
  10. if (submit)
  11.  ( left < 0 ) ? button.hide() : button.show();
  12.  });
  13.  });
Now i will teach you every line of code.
Line 1: Initializing the jquery function, to load jquery.
Line 2: Save comments data in a variable
Line 3: Save submit button movement in a variable.
Line 4: Define a variable, where you define, how much characters should be displayed.
Line 5: This div will be appeared after submitting comment
Line 6: Bind the textarea when anyone will loose focus to the textarea.
Line 7: Check the length of the comment typed.
Line 8: Minus the comment typed length by the specific length.
Line 9: Displaying a span html element, where characters counting will be displayed.
Line 10: Making condition, if submit button is pressed
Line 11: Then if remaining characters are less than 0, then hide the submit button, else show submit  button.
Line 12 and Line 13: Closing the jquery tags.

    No comments:

    Post a Comment