Kim
Kim

Reputation: 1156

Doesn't fire when using .on?

What I expect here is the function to fire when I click the class, but it doesn't happen! The a.button is dynamically created but IS on the page when it's fully loaded!

Any ideas why?

HTML:

   <a class="btn btn-success useImg">
          <i class="fa-icon-plus"></i>
          <span>Use</span>
   </a>

Jquery:

    $(".useImg").on("click", function(){
    alert("test");
    });

Upvotes: 0

Views: 63

Answers (5)

Animesh Nandi
Animesh Nandi

Reputation: 458

Try using $("body").on("click", ".useImg", function(){ alert("test"); });

and it is recommended that you use latest jquery lib http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js

Upvotes: 0

jfriend00
jfriend00

Reputation: 707326

Your code works perfectly fine in a standalone jsFiddle which you can see here.

Therefore, you must have one of these issues:

  1. You are trying to install the event handler before the DOM is ready or before the object exists.
  2. You have an error in your javascript that prevents the event handler from being installed.
  3. The actual code in your page or HTML is not the same as what you put in the question so there's some other issue that isn't disclosed.

You can protect against the first item by either putting your code in a $(document).ready() handler or by using delegated event handling.

For the second item, you have to check your browser error console for script errors.

Upvotes: 4

Geoff Appleford
Geoff Appleford

Reputation: 18832

You need to add the click event to another element further up the DOM tree and then filter it to work on your anchor element. That will fire for any elements with the .useImg class including those added dynamically.

$('body').on("click", ".useImg", function(){
    alert("test");
});

See http://api.jquery.com/on/

Make sure you wrap the code in the jQuery DOM Ready event to ensure the page has fully loaded. eg

$(document).ready(function() {
  $('body').on("click", ".useImg", function(){
        alert("test");
    });
});

Upvotes: 1

draxxxeus
draxxxeus

Reputation: 1523

$(document).ready(
  $('.useImg').click(function(){ alert(test); })
)

Upvotes: 0

Tamil Selvan C
Tamil Selvan C

Reputation: 20209

Try, when document is ready

$(function() {
 $(".useImg").on("click", function(){
    alert("test");
    });
}

Upvotes: 0

Related Questions