King Kong
King Kong

Reputation: 2915

Custom event in jquery

I am binding custom event on buttons to apply Jquery ui button plugin like :

      $(document).ready(function() { 
        $(".uibutton").live("CustomEvent", function() { $(this).button(); });
        $(".uibutton").trigger("CustomEvent");
      });

      <input type="button" class="uibutton" >

Now this works good for the button which are present in the MarkUP but the buttons which are created dynamically with class uibutton, this is not working. Can anybody please tell me why ?

Upvotes: 1

Views: 135

Answers (3)

ŁukaszBachman
ŁukaszBachman

Reputation: 33743

I know that you have mentioned using on() and it didn't turn out to be working, but please make sure you have used it like this:

$(document).on("click", ".uibutton", function() {
  /// My code....
});

And test it again.

The thing is, you need to add this handler to document element, which might not be obvious from documentation. Only that way you will be able to use on() just like live(). And please do use on() version, since latter will be removed from jQuery at one point or another.

Upvotes: 1

Peter Herdenborg
Peter Herdenborg

Reputation: 5972

As mentioned in the comments, the problem seems to be that even though the custom event is successfully bound even for dynamically created buttons with class uibutton, the event will still need to be triggered again every time a new button has been created. The .trigger() in your .ready() function will only affect the buttons existing at that point in time.

Upvotes: 2

Laughing
Laughing

Reputation: 211

$(".uibutton).trigger("CustomEvent");

There is missing closure quotation.

it should be like this:

$(".uibutton").trigger("CustomEvent");

try it.

Upvotes: 1

Related Questions