0

I'm trying to add a click event to .user that will change the background color of the entire page to green. I'm very new to jQuery, but the code looks right to me. When I click the .users button, nothing happens. Anyone have any ideas?

$(document).ready(function() {
  var $body = $('body')
  /*$body.html('');*/

  //  var currentView = "Twittler Feed"
  var currentView = $('<p>Twittler Feed</p>');
  var refreshTweet = function() {
    var index = streams.home.length - 1;
    var endInd = index - 10;
    while (index >= endInd) {
      var tweet = streams.home[index];
      var $tweet = $('<div class="tweets"><p class="posted-by"><button class="user">@' +
        tweet.user + '</button><p class="message">' + tweet.message +
        '</p><p class="time">' + /*$.timeago(tweet.created_at)*/ tweet.created_at + '</p></div>');
      currentView.appendTo('#sidebar')
      $tweet.appendTo($body);
      index -= 1;
    }
  }

  refreshTweet();

  $('.refresh').on('click', function() {
    if (document.getElementsByClassName('tweets')) {
      $('.tweets').remove();
    }
    var result = refreshTweet();
    $body.prepend(result);
  })

  $('.user').on('click', 'button', function() {
    currentView = this.user
    $('body').css('background-color', 'green');

  });
});
Praveen Kumar Purushothaman
  • 154,660
  • 22
  • 177
  • 226
  • I guess you are not supposed to break your code here: `var $tweet =` and your JS is screwed up here. Did you check the console for errors? – Praveen Kumar Purushothaman Jun 28 '17 at 20:06
  • console say anything? – tech2017 Jun 28 '17 at 20:08
  • `if (document.getElementsByClassName('tweets')) { $('.tweets').remove(); }` just call remove, why make multiple calls. – epascarello Jun 28 '17 at 20:09
  • The this.user makes no sense since the element you are referencing has no user property. Do you want to select the text of the element with the class user? – epascarello Jun 28 '17 at 20:10
  • You are not [delegating](https://learn.jquery.com/events/event-delegation/) the event corretly: the element `button` itself has the class `.user`. But the event should be binded to an element which already exist on page load – empiric Jun 28 '17 at 20:15
  • 1
    See here for duplicate (I linked wrong duplicate first time) : https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – freedomn-m Jun 28 '17 at 20:24
  • In summary, use event delegation: `$(document).on('click', '.refresh', function() ...` – freedomn-m Jun 28 '17 at 20:29
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Melvyn Jun 28 '17 at 22:34

0 Answers0