Micropost character countdown (Rails Tutorial, 2nd Ed, Chapter 10, Exercise 7)

后端 未结 2 1109
生来不讨喜
生来不讨喜 2020-12-11 10:06

I attempted the micropost character countdown in The Rails Tutorial (Chapter 10, Exercise 7) using the information here as a base and with some help from StackOverflow answe

2条回答
  •  半阙折子戏
    2020-12-11 10:32

    I am also going through this tutorial and found this post and while I like the css you added to make this look uniform (which I have taken to use as my own :)) I think your solution for this is over-complicated. For me it was simply two changes: the js script and adding the script to my view.

    My JS file: character_countdown.js

    function updateCountdown() {
      // 140 characters max
      var left = 140 - jQuery('.micropost_text_area').val().length;
      if(left == 1) {
        var charactersLeft = ' character left.'
      }
      else if(left < 0){
        var charactersLeft = ' characters too many.'
      }
      else{
        var charactersLeft = ' characters left.'
      }
      jQuery('.countdown').text(Math.abs(left) + charactersLeft);
    }
    
    jQuery(document).ready(function($) {
      updateCountdown();
      $('.micropost_text_area').change(updateCountdown);
      $('.micropost_text_area').keyup(updateCountdown);
    });
    

    and here is where I added it into the view

    
    <%= form_for(@micropost) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>
    

    Please let me know what you think :)

提交回复
热议问题