0

My code is adding a click event handler which filters messages on my feed to only show the username that has been clicked, however the click event is only triggered once. How can I make this click event to work every time a username is clicked?

Note: the newMessage function is a helper function for my renderFeed function.

var newMessage = function(index, user) {
  if (user !== undefined) {
    var message = streams['users'][user][index];
  } else {
    var message = streams.home[index];
  }
  var $message = $('<div class="message"></div>');
  var $username = $('<div class="username"></div>');
  $username.text('@' + message.user);
  $username.appendTo($message);
  $message.prependTo($messageStream);
}

$('.username').on('click', function() {
  $messageStream.html('');
  var $user = ($(this).attr('id'));
  renderFeed($user);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<body>
  <div id="app">
    <div id="feed">
      <div class="username">@user</div>
      <div class="message">Random message</div>
    </div>
  </div>
</body>
Stphane
  • 3,368
  • 5
  • 32
  • 47
M S
  • 21
  • 3
  • Hi! Please show the HTML related to the code in order to provide a [mcve] demonstrating the problem. Ideally, make it a **runnable** one using Stack Snippets (the `[<>]` toolbar button); [here's how to do one](https://meta.stackoverflow.com/questions/358992/). – T.J. Crowder Sep 30 '22 at 07:31
  • 1
    It looks a lot like you're **replacing** the `class="username"` element in the click handler. Attaching a handler attaches it to **that specific element**. If you destroy and replace that element, the handlers aren't magically attached to the new one. You might consider [event delegation](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events#event_delegation). – T.J. Crowder Sep 30 '22 at 07:32
  • the code seems to b running fine until it hits `$messageStream.html('');` and `renderFeed($user);`. which are undefined here. So having those could have helped. – Me Bottle O Scrumpy Sep 30 '22 at 08:03

0 Answers0