Wednesday, December 4, 2013

Applying Themes To Selected Text

When the user selects text in the browser, they generally get the browser default styles. That is, the default background color and the default text color for selected text. This is fine, in most cases. But if you want that extra level of polish added to your page, you can do so by using the CSS ::selected pseudo element. What's more is you can directly transfer jQuery UI theme property values to selected text using the following technique.

Here's what the selected text inside a widget looks like when styled by the browser.

And here's what the themed text selection looks like when using the start theme.

As you can see, the background color and the text color are sampled from the theme — the ui-state-highlight class to be exact. Let's take a look at how this works.

var $div = $( "<div/>" ).addClass( "ui-state-highlight " +
                                   "ui-helper-hidden" )
                        .appendTo( "body" ),
    bg = $div.css( "background-color" ),
    fg = $div.css( "color" );


$( "<style/>" ).text( ".ui-widget ::selection {" +
                      "background-color: " + bg + ";" +
                      "color: " + fg + "; }" )
               .appendTo( "head" );

$( "#accordion" ).accordion();

This code is the first to run once the DOM is ready. The first thing we're doing here is create a div element and storing it in the $div variable. This div has the ui-state-highlight applied to it, which sets the style properties we want to sample. The ui-helper-hidden class is used to hide the element, even though we're removing it instantly. Next, we sample the background-color and color CSS properties and store them in their respective bg and fg variables. Now that we have our property values, we're free to nuke the temporary div element.

Now we take our samples and inject them into a CSS rule in the page header. The selector used — .ui-widget ::selection — applies to selected text, but only if it's part of a widget. Like accordion content is. Note that this non-standard selector only has experimental support in some browsers, no support in others.

No comments :

Post a Comment