Search code examples
jqueryjquery-uijquery-ui-button

how to place irregular sized image into a jQuery UI button


Given a button of a fixed size and an image of an unknown size (but smaller dimensions than the button), how do I dynamically place that graphic onto the button?

This example only handles something icon sized, as does this example.

My own attempts end up cropping the image in the lower right. Hoping to get something robust that works across anything themeroller can spit out. Here is a live example demonstrating the problem: http://jsbin.com/iliqih/2/edit

<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.1/themes/base/jquery-ui.css"
/>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.1/jquery-ui.js"></script>
<script>

$(document).ready( function() {
var butt = $("<div class='butt' style='width:500; height:500px' />");
$('body').append(butt);
butt.button();

var cssKey = ".ui-icon.bigIcon";
$(".butt").button("option", {
    icons: {
        primary: 'bigIcon'
    },
    text: false
});

var imgUrl = "http://www.artisancomplete.com/wp-content/uploads/2011/03/testpattern-hd-1080-480x270.png";
var imgW = 480;
var imgH = 270;
var str = "<style type='text/css'> " + cssKey + " { background-image: url(" + imgUrl + ") !important; width:" + imgW + "px; height:" + imgH + "px; margin-left:-" + (imgW/2) + "; margin-top:-" + (imgH/2) + "} </style>";
$(str).appendTo("head");
});
</script>
</head>
</html>

Solution

  • The key is

    background-position:0

    Hereafter is a more replete example wherein previewW and previewH are the dimensions of your image.

    "<style type='text/css'>" + cssKey + " {width:" + previewW + "px; height:" + previewH + "px;margin-left:" + (-previewW/2) + "px;margin-top:" + (-previewH/2) + "px;background-position:0;background-image:url(" + imgSrc + ")!important;}</style>");