Add a JavaScript display to the Home page to count down from 140 characters. (Rails Tutorial, 2nd Ed, Chapter 10, Exercise 7)

前端 未结 7 1091
别跟我提以往
别跟我提以往 2021-02-04 08:32

This exercise was a bit tricky. Figured I\'d post my solution to see if anyone did it differently or if there\'s anyone who knows a better way.

I\'m not sure on best pra

7条回答
  •  再見小時候
    2021-02-04 09:39

    I don't know why, but that solution only worked for me using coffee script. I tried implementing it with javascript, but it somehow didn't display anything: nor the countdown, nor the fixed part of the text "characters remaining".

    So here's a recap of what I did.

    Step 1 : create a app/javascripts/microposts.js.coffee file

    updateCountdown = ->
      remaining = 140 - jQuery("#micropost_content").val().length
      jQuery(".countdown").text remaining + " characters remaining"
    
    jQuery ->
      updateCountdown()
      $("#micropost_content").change updateCountdown
      $("#micropost_content").keyup updateCountdown
    

    NB: Being that its placed in the app/javascripts folder, I didn't need to update the application.js file.

    Step 2 : update the _micropost_form.html.erb partial:

    <%= form_for(@micropost) do |f| %>
        <%= render 'shared/error_messages', object: f.object %>
        
    <%= f.text_area :content, placeholder: "Compose new micropost..." %>
    <%= f.submit "Post", class: "btn btn-large btn-primary" %> <% end %>

    step 3: implement a bit of css to the custom_css.css.scss file

    /* micropost jQuery countdown */
    
    .countdown {
      display: inline;
      padding-left: 10px;
      color: $grayLight;
    }
    

    Step 4: enjoy the result and be happy that it all works out :)

提交回复
热议问题