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

前端 未结 7 1089
别跟我提以往
别跟我提以往 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:38

    I used Brett's code to get me through this exercise in the Rails Tutorial, though I have a minor change. I had problems with the text disappearing from the .countdown element when I navigated to a different page, then back to Home. With some minor research and help from another answer on SO I realized that the cause was Turbolinks. My change to Brett's code, binding to page:change event instead of to ready, is below. I hope this helps some other folks.

    function updateCountdown() {
      // 140 is the max message length
      var remaining = 140 - jQuery('#micropost_content').val().length;
      jQuery('.countdown').text(remaining + ' characters remaining');
    }
    
    function micropostChange() {
      $('#micropost_content').change(updateCountdown);
    }
    
    function micropostKeyup() {
      $('#micropost_content').keyup(updateCountdown);
    }
    
    jQuery(document).ready(function($) {
      updateCountdown();
      micropostChange();
      micropostKeyup();
      jQuery(document).on('page:change', function($) {
        updateCountdown();
        micropostChange();
        micropostKeyup();
      });
    });
    

提交回复
热议问题