Momo1987
Momo1987

Reputation: 544

On event doesn't work

A simple question:

When I use

$(document).on('click', '.btn-del-top', function(e) {}) 

everyhing work, but if I use

$('.btn-del-top').on('click', function(e) {}) 

nothing work.Is there some explanation?

Upvotes: 1

Views: 79

Answers (3)

T.J. Crowder
T.J. Crowder

Reputation: 1075209

The main reason would be that when you run the second code snippet, the elements don't exist yet, so they aren't found, and so they aren't hooked up. The first code snippet doesn't look for them until it sees a click on document (e.g., probably much later).

The reason they aren't found may vary:

  1. If your code looking for them is in a script tag above where they're defined in the HTML, they won't exist yet. For instance:

    <!-- Won't work, the element doesn't exist when you look for it -->
    <script>
    $('.btn-del-top').on('click', function(e) {})
    </script>
    <span class="btn-del-top">...</span>
    

    But:

    <!-- Will work, the element exists when you look for it -->
    <span class="btn-del-top">...</span>
    <script>
    $('.btn-del-top').on('click', function(e) {})
    </script>
    

    And:

    <!-- Will work also work, jQuery will call your code later when
         all elements in the markup have been created -->
    <script>
    $(function() { // shortcut for `$(document).ready(...)`
        $('.btn-del-top').on('click', function(e) {})
    });
    </script>
    <span class="btn-del-top">...</span>
    
  2. If you create them later using code, they won't exist earlier when you try to hook them up.

Upvotes: 0

Tdelang
Tdelang

Reputation: 1308

If you're adding .btn-del-top dynamically, the second one binds before that element exists, thus it doesn't bind.

Upvotes: 0

Arun P Johny
Arun P Johny

Reputation: 388416

it could be because btn-del-top elements are created dynamically or are created after the $('.btn-del-top').on('click', function(e) {}) code is executed.

Demo1: In this case it is not working because the code is not inside dom ready

Upvotes: 3

Related Questions