Search code examples
javascriptajaxgoogle-closuregoogle-closure-library

Creating an instance of goog.ui.Button with an image file


I'm relatively new to the Google Closure library and my current obstacle is getting a button to render programmatically with an image (as opposed to text). I've tried adding a img tag as the content of the button:

var image = goog.dom.createDom('img', { 'src' : 'foo.png' });
var button = new goog.ui.Button(image);

However, although a blank button does render in the page no image appears. An inspection of the generated HTML shows a button tag with no contents.

I've also considered adding a style attribute that specifies background-image. However, it's not clear to me how to accomplish this through the Button API.

Any thoughts or examples on how to accomplish this? Appreciate the help.

EDIT: Here's the solution I arrived at with Dave Paroulek's assistance:

var button = new goog.ui.CustomButton();
button.render(goog.dom.getElement('button-row'));
var style = button.getElement().style;
style.backgroundImage = 'url(foo.png)';
style.backgroundPosition = 'center center';
style.backgroundRepeat = 'no-repeat';

Solution

  • CustomButton seems to work:

    var image = goog.dom.createDom('img', { 'src' : '/images/foo.png' });
    var button = new goog.ui.CustomButton(image);
    

    I'm not sure specifically why it doesn't work with Button, but noticed that Button renders a <button> and CustomButton renders several <div> elements that are styled to look like a button, so maybe that has something to do with it?

    Also, if you want to use background-image, then you can try this:

    var div = goog.dom.createDom('div', { 'class' : 'icon goog-inline-block' });
    span = goog.dom.createDom('span', { 'style': 'vertical-align:middle'}, 
                                  'Button with css image');
    
    button = new goog.ui.CustomButton([div, span]);
    var btn2 = goog.dom.$('button2');
    button.render(btn2);
    

    Then, add css like this:

    .icon {
      height: 16px;
      width: 16px;
      margin: 0 1px;
      background-image: url(/images/foo.png);
      background-repeat: no-repeat;
      vertical-align: middle;
    }