Thursday, December 5, 2013

Themed Resizable Helpers

The resizable interaction widget found in jQuery UI guides users by displaying a helper element. This is just a transient div, styled so that the user can see an outline of the new size once the mouse is released. This is especially useful when the animate option is set to true — you can see the outline, and the space is filled with the resize animation. These helper elements don't, however, use styles from the theme framework. But we can change that.

Take a look at this example. It sets the animate option to true, then supplies a start callback function to update the helper styles. It does so by sampling the styles of the element to be resized, which makes the assumption that the element is in fact using classes from the jQuery UI CSS theme. Here's what the result looks like using the darkness theme.



And here's the same interaction using the sunny theme.


Let's take a look at the start callback function to better understand how these changes in resizable helper styles come to into being.

start: function( e, ui ) {
        
    var border = ui.element.css( "border-color" ),
        background = ui.element.css( "background-color" );
        
    background = ( /\((.+)\)/ ).exec( background )[ 1 ];

    ui.helper.css({
        border: "2px dotted " + border,
        background: "rgba( " + background + ", 0.1 )"
    });
        
    if ( ui.element.hasClass( "ui-corner-all" ) ) {
        ui.helper.addClass( "ui-corner-all" );    
    }
        
}

The two CSS properties we want sampled from the element are border-color and background-color. These are stored in their respective variables — border and background. Since the background value is going to be in the form of rgb(0, 0, 0), we need a regular expression that parses out just the 3 numerical values — you'll see why in a moment.

The ui.helper property is the element created for us by the widget, and it's the one we want to update the styles on. We first add the border property, making it 2px dotted, and the sampled border color. Next we construct the background property value. You'll notice that we're building an rgba() value, adding an alpha channel transparency, but still using the same background color as the element. Without this transparency, the background color of the helper would be indistinguishable from that of the element.

The finishing touch on this style addition is probing the element for the existence of the ui-corner-all class. If it's there, we add it to the helper too, so that it shares the same corner styles as the theme in use.

No comments :

Post a Comment