How do I add a custom icon to a standard jQuery UI theme?
Asked Answered
S

8

45

It is easy to use one of the icons available from the standard icon set:

$("#myButton").button({icons: {primary: "ui-icon-locked"}});

But what if I want to add one of my own icons that is not part of the framework icon set?

I thought it would be as easy as giving it your own CSS class with a background image, but that doesn't work:

.fw-button-edit {
    background-image: url(edit.png);
}

Any suggestions?

Semiannual answered 1/10, 2010 at 2:52 Comment(0)
D
64

I could also recommend:

.ui-button .ui-icon.your-own-custom-class {
    background-image: url(your-path-to-normal-image-file.png);
    width: your-icon-width;
    height: your-icon-height; 
}

.ui-button.ui-state-hover .ui-icon.your-own-custom-class {
    background-image: url(your-path-to-highlighted-image-file.png);
    width: your-icon-width;
    height: your-icon-height; 
}

then just type in the JS code:

        jQuery('selector-to-your-button').button({
        text: false,
        icons: {
            primary: "you-own-cusom-class"   // Custom icon
        }});

It worked for me and hope it works for you too!

Danutadanya answered 7/5, 2011 at 10:28 Comment(3)
Thanks! Is this documented in the jquery-ui docs? I can't find it mentioned anywhere.Leftwich
How could anyone have it work with a reference to you-own-cusom-class ? Still, the lead is good.Archiphoneme
Late editing — But for me the CSS width and height properties seem utterly ineffective.Archiphoneme
C
14

I believe the reason why his won't work is because you're icon's background-image property is being overridden by the jQuery UI default sprite icon background image. The style in question is:

.ui-state-default .ui-icon {
    background-image: url("images/ui-icons_888888_256x240.png");
}

This has higher specificity than your .fw-button-edit selector, thus overriding the background-image proerty. Since they use sprites, the .ui-icon-locked ruleset only contains the background-position needed to get the sprite image's position. I believe using this would work:

.ui-button .ui-icon.fw-button-edit {
    background-image: url(edit.png);
}

Or something else with enough specificity. Find out more about CSS specificity here: http://reference.sitepoint.com/css/specificity

Cida answered 1/10, 2010 at 3:6 Comment(1)
Doesn't Jquery UI apply the background to a span that's inserted in the element?Autarky
P
3

This is based on the info provided by Yi Jiang and Panayiotis above, and the jquery ui button sample code:

As I was migrating an earlier JSP application that had a toolbar with images per button, I wanted to have the image inside the button declaration itself rather than create a separate class for each toolbar button.

<div id="toolbarDocs" class="tableCaptionBox">
    <strong>Checked Item Actions: </strong>

    <button id="btnOpenDocs" data-img="<s:url value="/images/multi.png"/>">Open Documents</button>
    <button id="btnEmailDocs" data-img="<s:url value="/images/email.png"/>">Attach to Email</button>
</div>

Of course there were plenty more buttons than just the two above. The s tag above is a struts2 tag, but you could just replace it with any URL

        <button id="btnOpenDocs" data-img="/images/multi.png">Open Documents</button>

The below script looks for the attribute data-img from the button tag, and then sets that as the background image for the button.

It temporarily sets ui-icon-bullet (any arbitrary existing style) which then gets changed later.

This class defines the temporary style (better to add further selectors for the specific toolbar if you plan to use this, so that the rest of your page remains unaffected). The actual image will be replaced by the Javascript below:

button.ui-button .ui-icon {
    background-image: url(blank.png);
    width: 0;
    height: 0; 
}

and the following Javascript:

 $(document).ready(function () {
    $("#toolbarDocs button").each(
          function() { 
            $(this).button(
              { text: $(this).attr('data-img').length === 0? true: false, // display label for no image
               icons: { primary: "ui-icon-bullet"  }
              }).css('background-image', "url(" + $(this).attr('data-img') +")")
               .css('background-repeat', 'no-repeat');
            });
  });
Prefix answered 18/10, 2011 at 12:16 Comment(2)
this version works for me as it allows me to use an image that is defined using a URL rather than a CSS class.Brion
The data- attribute is part of HTML 5 but as this SO link shows, also works for the earlier browsers as well. I just found out its used by jquery internally, and jquery has a data() method. We can use the method .data('img') instead of .attr('data-img')Prefix
R
3

The solution at this link worked great for me: http://www.jquerybyexample.net/2012/09/how-to-assign-custom-image-to-jquery-ui-button.html

$(document).ready(function() {
    $("#btnClose")
    .text("")
    .append("<img height='100' src='logo.png' width='100' />")
    .button();
});​
Rueful answered 1/12, 2014 at 19:58 Comment(1)
I had to use single quotes inside the append... but simple and it works...Bluebell
E
1

My solution to add custom icons to JQuery UI (using sprites):

CSS:

.icon-example {
    background-position: 0 0;
}

.ui-state-default .ui-icon.custom {
    background-image: url(icons.png);
}

.icon-example defines position of icon in custom icons file. .ui-icon.custom defines the file with custom icons.

Note: You may need to define other JQuery UI classes (like .ui-state-hover) as well.

JavaScript:

$("selector").button({
    icons: { primary: "custom icon-example" }
});
Ephod answered 22/7, 2013 at 14:12 Comment(1)
your answer is uncomprenssibleRegistration
S
0

Building on msanjay answer I extended this to work for custom icons for both jquery ui buttons and radio buttons as well:

<div id="toolbar">
    <button id="btn1" data-img="/images/bla1.png">X</button>
    <span id="radioBtns">
      <input type="radio" id="radio1" name="radName" data-mode="scroll" data-img="Images/bla2.png"><label for="radio1">S</label>
      <input type="radio" id="radio2" name="radName" data-mode="pan" data-img="Images/bla3.png"><label for="radio2">P</label>
    </span>
</div>    

$('#btn1').button();
$('#radioBtns').buttonset();

loadIconsOnButtons('toolbar');

function loadIconsOnButtons(divName) {
    $("#" + divName + " input,#" + divName + "  button").each(function() {
      var iconUrl = $(this).attr('data-img');
      if (iconUrl) {
        $(this).button({
          text: false,
          icons: {
            primary: "ui-icon-blank"
          }
        });
        var imageElem, htmlType = $(this).prop('tagName');
        if (htmlType==='BUTTON') imageElem=$(this);
        if (htmlType==='INPUT') imageElem=$("#" + divName + " [for='" + $(this).attr('id') + "']");
        if (imageElem) imageElem.css('background-image', "url(" + iconUrl + ")").css('background-repeat', 'no-repeat');
      }
    });
}
Sibylle answered 9/4, 2014 at 5:8 Comment(0)
C
0
// HTML

<div id="radioSet" style="margin-top:4px; margin-left:130px;" class="radio">
      <input type="radio" id="apple" name="radioSet"  value="1"><label for="apple">Apple</label>
      <input type="radio" id="mango" name="radioSet" value="2"><label for="mango">Mango</label>
</div>


// JQUERY

// Function to remove the old default Jquery UI Span and add our custom image tag

    function AddIconToJQueryUIButton(controlForId)
    {
        $("label[for='"+ controlForId + "'] > span:first").remove();
        $("label[for='"+ controlForId + "']")
        .prepend("<img position='fixed' class='ui-button-icon-primary ui-icon' src='/assets/images/" + controlForId + ".png' style=' height: 16px; width: 16px;' />");

    }

// We have to call the custom setting to happen after document loads so that Jquery UI controls will be there in place

   // Set icons on buttons. pass ids of radio buttons
   $(document).ready(function () {
                 AddIconToJQueryUIButton('apple');   
                 AddIconToJQueryUIButton('mango');   
    });

   // call Jquery UI api to set the default icon and later you can change it        
    $( "#apple" ).button({ icons: { primary: "ui-icon-gear", secondary: null } });
    $( "#mango" ).button({ icons: { primary: "ui-icon-gear", secondary: null } });
Cthrine answered 19/9, 2014 at 23:16 Comment(0)
R
0

in css

.ui-button .ui-icon.custom-class {
    background-image: url(your-path-to-normal-image-file.png);
    width: your-icon-width;
    height: your-icon-height; 
}

.ui-state-active .ui-icon.custom-class, .ui-button:active .ui-icon.custom-class {
    background-image: url(your-path-to-highlighted-image-file.png);
    width: your-icon-width;
    height: your-icon-height; 
}

in HTML

<button type="button" class="ui-button ui-widget ui-corner-all">
    <span class="custom-class"></span> CAPTION TEXT
</button>

in JavaScript

$("selector").button({
    icons: { primary: "custom-class" }
});
Rutherford answered 22/7, 2016 at 16:31 Comment(1)
Your answer would benefit from explanation.Thyrotoxicosis

© 2022 - 2024 — McMap. All rights reserved.