Character countdown like on twitter

后端 未结 9 947
栀梦
栀梦 2020-12-02 06:54

How can I make a \"remaining characters\" countdown like the one on Twitter with jQuery? And also limit the input to a textarea.

9条回答
  •  半阙折子戏
    2020-12-02 07:06

    Make a span and textarea and give them unique selectors (using an ID or class) like so:

    
    
    

    And then make an update function like so:

    function updateCountdown() {
        // 140 is the max message length
        var remaining = 140 - jQuery('.message').val().length;
        jQuery('.countdown').text(remaining + ' characters remaining.');
    }
    

    And make that function run when the page is loaded and whenever the message is changed:

    jQuery(document).ready(function($) {
        updateCountdown();
        $('.message').change(updateCountdown);
        $('.message').keyup(updateCountdown);
    });
    

    Visit an example and view the source. jQuery makes things like this very simple.

提交回复
热议问题