Search code examples
javascriptjqueryasp.net-mvcjquery-uijquery-ui-button

How to make all buttons(even dynamically created) in an application follow jquery button widget without calling .button() multiple times


I am new to stack overflow and this is my first question. Pardon me for any mistakes. This question is more generic but i tried to search for an answer but could not find it.

Say i have a page and i am using jquery ui button() widget for all the button. What happens is i have a specific class defined for all the buttons on my page. So i can just specify $('.myButtonClass').button(); but whenever i render partial views which has button again i have to do the same thing in the partial views. Is there any way i can globally specify a transition for button or any element for that matter.

Here is a sample Fiddle which adds buttons on click. But the added buttons are not transitions as button widgets(I do not want to use clone).

http://jsfiddle.net/wjxn8/

$('.clsTest').button().click(function(){
    $(this).after('<input type="button" value="Added" class="clsTest"/>');
});

Is this possible without:- 1) Adding the css classes for a button widget manually for all the buttons created. 2) Tracking DOM Changes using Javascript and perform transitions for all the button elements.

Thanks for your help!!!


Solution

  • Since you were looking for something else, why not trigger a custom event when you load partials or whatever:

    $('.clsTest').button().click(function(){
        $(this).after('<input type="button" value="Added" class="clsTest"/>').trigger('addButtonUI');
    });
    $(document).bind('addButtonUI',function(){
        $('.clsTest').button();
    });
    

    http://jsfiddle.net/wJXN8/3/

    If you trigger your event and have the document listening for it, then you can do whatever you would like. I could have put in there the ability to add more buttons as well, but this should get the point across.

    What you are asking for, some event when a button is added.... you would need to come up with that yourself and trigger it when a button is added. There is this: How to detect new element creation in jQuery? which talks about a specific event that is triggered when new elements are added to the DOM. Haven't tested it, and it looks like it may not work on IE.