0

I have a list of unordered list where I want to add an event listener but for some reason it doesn't listen to clicks.

Here's my code:

$('li.lists').on('click', function() {
  console.log('it listens here')
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside class="room-list" id="room-list">
  <div class="rooms">
    <h2><i class="fa fa-address-book-o"></i> Room List</h2>
  </div>
  <ul class="list-item-room">
    <li class="lists">
      <img src="images/hr_avatar.png">
      <div class="room-details">
        <div class="room-name">
          zzzzz........
        </div>
        <div class="status">
          <i class="fa fa-circle online"></i> online
        </div>
      </div>
    </li>
    <li class="lists">
      <img src="images/hr_avatar.png">
      <div class="room-details">
        <div class="room-name">
          lobby
        </div>
        <div class="status">
          <i class="fa fa-circle online"></i> online
        </div>
      </div>
    </li>
    <li class="lists">
      <img src="images/hr_avatar.png">
      <div class="room-details">
        <div class="room-name">
          zzzzz........
        </div>
        <div class="status">
          <i class="fa fa-circle online"></i> online
        </div>
      </div>
    </li>
    <li class="lists">
      <img src="images/hr_avatar.png">
      <div class="room-details">
        <div class="room-name">
          lobby
        </div>
        <div class="status">
          <i class="fa fa-circle online"></i> online
        </div>
      </div>
    </li>
  </ul>
</aside>

Suppose to be this must console log it listens here whenever a list was click but it doesn't. Any idea why? Thanks!

F0XS
  • 1,271
  • 3
  • 15
  • 19
  • 1
    Presumably because `$('li.lists')` didn't find any elements, and so didn't hook up any event handler. The usual cause of this (see the linked question's answers) is that you ran the code before the elements existed. Make sure the code is in a `script` tag at the very **end** of the `body`, just before the closing `

    ` tag, so that all of the elements defined by the HTML above it have been created before it runs.

    – T.J. Crowder Jan 24 '18 at 08:00
  • You can use this as well: $( document ).ready(function() { $('li.lists').on('click', function() { console.log('it listens here') }); }); – D. Braun Jan 24 '18 at 08:02
  • It's inside the document ready function already. –  Jan 24 '18 at 08:09

0 Answers0