Apply CSS to jQuery Dialog Buttons

button, css, dialog, jquery, jquery-ui

Solution

I’m reposting my answer to a similar question because no-one seems to have given it here and it’s much cleaner and neater:

Use the alternative `buttons` property syntax:

$dialogDiv.dialog({
    autoOpen: false,
    modal: true,
    width: 600,
    resizable: false,
    buttons: [
        {
            text: "Cancel",
            "class": 'cancelButtonClass',
            click: function() {
                // Cancel code here
            }
        },
        {
            text: "Save",
            "class": 'saveButtonClass',
            click: function() {
                // Save code here
            }
        }
    ],
    close: function() {
        // Close code here (incidentally, same as Cancel code)
    }
});

Problem

So I currently have a jQuery dialog with two buttons: Save and Close. I create the dialog using the code below: ``` $dialogDiv.dialog({ autoOpen: false, modal: true, width: 600, resizable: false, buttons: { Cancel: function() { // Cancel code here }, 'Save': function() { // Save code here } }, close: function() { // Close code here (incidentally, same as Cancel code) } }); ``` However, both buttons are the same color when this code is used. I'd like my Cancel button to be a different color than my Save. Is there a way to do this using some built in jQuery options? I didn't get much help from the documentation. Note that the Cancel button I'm creating is a pre-defined type, but 'Save' I'm defining myself. Not sure if that will have any bearing on the issue. Any help would be appreciated. Thanks. UPDATE: Consensus was that there were two roads to travel here: - Inspect the HTML using a Firefox plugin like firebug, and note the CSS classes that jQuery is applying to the buttons, and take a stab at overriding them. Note: in my HTML, both buttons were used the exact same CSS classes and no unique IDs, so this option was out. - Use a jQuery selector on dialog open to catch the button that I wanted, and add a CSS class to it then. I went with the second option, and used the jQuery find() method as I think this is more appropriate than using :first or :first-child b/c the button that I wanted to change wasn't necessarily the first button listed in the markup. Using find, I can just specify the name of the button, and add CSS that way. The code I ended up with is below: ``` $dialogDiv.dialog({ autoOpen: false, modal: true, width: 600, resizable: false, buttons: { Cancel: function() { // Cancel code here }, 'Save': function() { // Save code here } }, open: function() { $('.ui-dialog-buttonpane').find('button:contains("Cancel")').addClass('cancelButtonClass'); } close: function() { // Close code here (incidentally, same as Cancel code) } }); ```

Original source