Archive

Archive for the ‘HTML’ Category

Tip: Using Spark Conditionals to Toggle CSS and JavaScript

January 3, 2012 Comments off

The conditional attribute is a fantastic shortcut to toggle CSS, input boxes, and other elements on a page–and is something I don’t see used in very many examples. One of my favorites is applying classes to an element based on a output model property, such as a permission boolean.

Here’s an example.

In a recent project, a dashboard screen had several charts that toggled on and off based on the user’s preference. Rather than rebuild the screen each time, each class simply toggled an ‘enabled’ class based on a Model.{Property}.

<div class="charts">
    <div id="enteredbycount" class="loading enabled?{Model.ShowEnteredBy}"
		style="inlineChart">
	</div>
    <div id="schoolcount" class="loading enabled?{Model.ShowSchoolCount}"
		style="inlineChart">
	</div>
</div>

The Spark Conditional only renders the text preceding the conditional ?{} if the condition is true. In this example, if our Model.ShowSchoolCount returns false, enabled never renders and our chart (due to some styling), remains hidden and never posts back to the server to get the chart data (saving an unnecessary AJAX call).

By toggling a class, you can trigger a certain set of styles, events using JavaScript, or most anything else you can dream up.

Using .less To Simplify BluePrintCSS

December 17, 2009 2 comments

For the past few projects, I’ve used BluePrintCSS and really liked the experience.  It forced me both to conquer my CSS layout fears (tables no more) and standardize a few of my formatting techniques that we use on our internal and external applications.  Good deal all around.

The one caveat that I really… really didn’t like was how I had to name things.

The clean class codes and IDs that I had…

<div class="page">
    <div class="header">
        <div class="title">
            <h1>${H(ApplicationName)}</h1>
        </div>
        [...]
    </div>
</div>

Turned into long, drawn out classes…

<div class="container">
    <div class="span-24">
        <div class="prepend-1 span-12 column">
            <h1>${H(ApplicationName)}</h1>
        </div>
    </div>
</div>

Without the BluePrintCSS guide or the CSS files available, you couldn’t look at the classes and tell much of what was going on… and it wasn’t descriptive like ‘header’ and ‘title’.

Welcome To .less (dotless)

I stumbled onto .less (aka dotless, dotlesscss, that shizzle css thingy) back in November and thought “hey, that’s cool… that’s how CSS should work” and didn’t give it much more thought.  Shortly after fav’ing it in github, I noticed they pushed an update targeting BluePrintCSS operability.  Cool–I’ve GOT to try this out.

Getting Started with .less

The instructions on the home page (right side of the screen) is all you need.  Clone, compile, update web.config and start go!

The Benefits

So what’s the big hype?  This:

1. Import your BluePrintCSS file into your .less file (for me, it’s site.less).

@import “screen.css”;

2. Simply reference any of the BluePrintCSS class styles as part of your custom styles.

#header {
    #title {
        .span-10;
        .column;
    }
 
    #menucontainer {
        .span-14;
        .column;
        .last;
        text-align: right;
    }
}
 
#left-content {
    .span-18;
    .column;
}
 
#right-boxes {
    .span-6;
    .column;
    .last;
}

Then a miracle occurs...3. “Then a miracle occurs…”

When dotless’ HttpHandler hits your .less file (or your use dotless.Compiler), it translates those referenced styles into their actual CSS tags.


#header #title{width:390px;float:left;margin-right:10px;}

Nice.  Plain and simple (and miraculous).

Lessons Learned

Some “lessons learned” so far:

1. Order matters.  Referencing a style before you’ve ‘created’ it will bork the interperter. So @imports always go at the top and if you’re referencing within the same .less file, keep things in order.

2. Pre-compiling is fun.  For now, I’m pre-compiling my .less files without using the handler and simply sending the css file up to our web server.  This is easily taken care of with either a MS Build task or psake task.  Here’s how an example of a quick MS Build task that references the dotless.Compiler in the solution’s “tools” directory.

$(SolutionDir)Tools\dotLess\dotless.compiler.exe -m $(ProjectDir)content\css\site.less $(ProjectDir)content\css\site.css

3. .less files need to be ‘Content’. Since VS2008 is stupid, .less files (like .spark views, etc) need to be explicitly set to have a Build Action of ‘Content’ so that the publishing process sends them up to the web server.  If you’re publishing via psake or another automation tool, then ignore this. ๐Ÿ˜‰

That’s it for now.  Hit up the project site, peruse and clone the github repo, and join the discussion for .less and (finally) start applying some DRY to your CSS.

Reusable ‘Controls’ with Sprites, CSS, and Spark Partials

October 2, 2009 Comments off

I came across SilkSprite during some of my work with BluePrintCSS and fell in love.  I’ve used the FamFamSilk icons for ages and, with a current project, wanted to implement some instant CSS buttons and menu items using those icons.

So, with CSS-fu in hand, here’s how the button turned out.

First, creating a simple CSS button style:

.button

{

    display: inline-block;

    font-weight: bold;

    font: bold .85em/2.5em Verdana, Helvetica, sans-serif;

    text-decoration: none;

    text-indent: 10px;

    width: 150px;

    height: 2.5em;

    color: #555555;

    background-color: #EAEAD7;

    border: #CCCCCC solid 1px;

    -moz-border-radius: 5px;

    -webkit-border-radius: 5px;

}

 

.button:hover

{

    background-color: #F3F3E9;

    color: #737373;

    cursor: pointer;

}

This button is pretty simple and standard—nothing fancy.  The most important tag in there is display: inline-block as this allows our buttons to share the same row and not stack on top of each other (like float:left would cause).

Hover Off: CSS Button - Hover Off

Hover On: CSS Button - Hover On

Second, because I needed to include the icon INSIDE another container (the button), I modified the original SilkSprite ss_sprite and removed a bit of the extra padding.

.sprite

{

    display: inline-block;

    overflow: hidden;

    background-repeat: no-repeat;

    background-image: url(/content/img/sprites.png);

    padding-left: 25px;

    padding-top: 2px;

    height: 16px;

    max-height: 16px;

    vertical-align: middle;

}

The important thing to note here is the padding-top and the height attributes.  Until I’m lead into the light and improve my CSS-fu, I’m compensating for the font height differences by using padding-top.  e.g. I want the icon to truly show up in the “middle”… and vertical-align just wasn’t pushing it far enough.

We’ll come back to actually working with SilkSprite in a moment, let’s work up a quick Spark partial view to display our results.  Now, you could do this without the partial views—just replace my Spark variables with the actual text we’re passing to them.  I’ll provide both examples.

Our button needs three elements to be useful:

  1. An ID so that we can call it from jQuery or your client-side query engine of choice,
  2. A Sprite Name, such as ss_add, etc.  These are provided by SilkSprite.
  3. The button text.

So, knowing that, a basic button could be rendered using:

<div id=”my-button” class=”button”>

    <span class=”sprite ss_add” />Add Activity

</div>

We can simply substitute out the variable elements (id, sprite class, and text) and create a Spark partial view (named _styledButton.spark and located in the /Shared view folder).

<div id=”${id}class=”button”>

    <span class=”sprite ${sprite}“></span>${text}

</div>

In our views, it’s easy to create a button:

<styledButton text=”‘Add Activity‘” id=”‘my-button‘” sprite=”‘ss_page_add‘” />

Note: You need to surround your text with single quotes (‘text’) to inform the Spark engine that the information contained in your variables is a string.

Now, we have shiny, icon’d buttons:

Hover Off:

Hover On:

Categories: HTML, MVC, Spark View Engine

Rendering the Web Equally on Mobile Devices

June 26, 2009 Comments off

I’ve been digging through the Interwebs for a while now and, I thought, had worked out all of the “kinks” of rendering on a mobile device—specifically iPhones.

The special ‘viewport’ meta tag means the world to iDevices.

meta name=“viewport” content=“width = device-width” />

I’m faced with a new challenge—the Palm Pre’s built-in web browser.  My shiny new phone is great, but it isn’t without glitches.

The first glitch I’ve found appears to be a DNS issue— http://myserver/web won’t resolve; however, http://123.45.67.89/web will.  It seems to be touchy.  Most of our webs work just fine, others don’t.  I haven’t narrowed it down to a single server or architecture as it seems to be a bit of everything.  Wonky.

The next glitch is more important—the rendering.  One of our tools is a simple form-based tool that looks great on the iPhone; however, renders partial screen and “garbles” when you move around the screen.

Palm Pre:

Garbled image

iTouch/iPhone:

I’ve also found that anything in an ASP.NET Update Panel (like those Select buttons) are unusable.  Other webs I’ve used (Bank of America, etc) use AJAX just fine, so I don’t think it’s that—probably a coding issue I need to dig into and resolve.

UPDATE: Explicitly adding “LoadScriptsBeforeUI=’true’” to the ASP.NET ScriptManager seems to help with this.. a little.

Anyone else worked specifically with the Pre devices and rendering?  I’d appreciate any meta tags or layout ideas that worked. ๐Ÿ™‚  The Pre isn’t a common device in our organization—yet.

Implementing IEPNGFix as a Reusable Control

January 30, 2009 4 comments

Even with IE 8.0 on the horizon, a great deal of our internal users are still using IE 5.5 and 6.0.  While, for the most part, our current coding techniques are unaffected, we did move to using PNG files quite a while ago and are faced with rendering issues as the target audience for a few of our produces expands.

To solve those issues, I’ve been using TwinHelix’s IE PNG Fix behavior with a great deal of success; however, I dislike keeping track of multiple files and references between projects.  It made more sense to make it a reusable control and include it in our shared architecture library.  When Angus releases a new implementation, then I only need to update the control and push out the updated libraries rather than touching HTML in each project.

Here’s how:

1. Download the latest version of IE PNG Fix from here.

2. Add the IEPngFix.htc, blank.gif, and IEPngFix_tilebg.js (if using 2.0 Alpha 3) into your project.  Mark all three files as Embedded Content.

3. Create a basic CSS file that can be added to pages and call the IEPngFix behavior.  Use the full path to the Web Resource (we’ll add those in the next step).  It’s sensitive to the namespace of your project.

img, div, .pngfix, input {

    behavior: url(‘<%=WebResource(“Resources.IEPngFix.htc”)%>’);

}

3. Modify the Properties/AssemblyInfo.cs file and add the approprate Web References.

[assembly: WebResource(“Resources.IEPngFix.css”, “text/css”,

       PerformSubstitution = true)]

[assembly: WebResource(“Resources.IEPngFix.htc”, “text/x-component”,

       PerformSubstitution = true)]

[assembly: WebResource(“Resources.IEPngFix_blank.gif”, “image/gif”)]

[assembly: WebResource(“Resources.IEPngFix_tilebg.js”, “text/javascript”)]

Notice that the HTC behavior file is an “x-component”.  For a full list of MIME references, check out the w3schools.com.  Also, perform substitution allows us to use dynamic calls of resources—within resources, such as in our CSS file.

4. Create a new class that inherits from CompositeControl.  This control will add the javascript and CSS references into our projects.  Override the OnPreRender method and populate the calling Page’s header with the links to our two files.

protected override void OnPreRender(EventArgs e)

{

       // Base Code: http://www.twinhelix.com/css/iepngfix/

       // Include JavaScript for tiled background support.

       string javascriptInclude =

              Page.ClientScript.GetWebResourceUrl(GetType(),

             “Resources.IEPngFix_tilebg.js”);

           

       var jsLink = new HtmlLink

              {

                     Href = javascriptInclude

              };

       jsLink.Attributes.Add(“type”, “text/javascript”);

       Page.Header.Controls.Add(jsLink);

           

       // Include Css file that calls HTC.

       string cssInclude =

              Page.ClientScript.GetWebResourceUrl(GetType(),

             “Resources.IEPngFix.css”);

           

       var cssLink = new HtmlLink

              {

                     Href = cssInclude

              };

       cssLink.Attributes.Add(“rel”, “stylesheet”);

       cssLink.Attributes.Add(“type”, “text/css”);

       Page.Header.Controls.Add(cssLink);

 

       base.OnPreRender(e);

}

That’s it.  Build and add the new control to your project.  You can then add a new forms page and drop the control into the page.  I prefer, however, to keep a “DefaultPage” and inherit my pages from it—add once, apply to all. ๐Ÿ™‚

protected void Page_Load(object sender, EventArgs e)

{

       Page.Controls.Add(new IEPngFix());

}

Here we can see the rendered control. The PNG has a transparent background and without IEPngFix shows up as a white box rather than seeing the black background of the page.  Works like a champ!

IEPngFix in Action

Thanks again to Angus Turnbull for this excellent behavior!

Tags: , , , ,

Setting the ViewPort for iPhone/iTouch Ready Web Sites

January 13, 2009 Comments off

Scenario:

After rolling out two new web applications targeted for WindowsMobile and Blackberries, we had a request to test and support Apple iPhone/iTouch devices.  Not a big deal, or so I thought.

Unfortunately, Safari on these devices displayed properly, but every page required zooming and was almost impossible to read.  There had to be a way to get Safari to respect the set width of the page rather than scale it out.

Solution:

Michael: “are you setting the viewport?”

Thanks to Google and a bit of help from a friend (thanks Michael!), the mysterious solution was just a meta tag away.  The best place to start would be the “Safari Web Content Guide for iPhone OS”.  I had found bits of this document elsewhere, but the information about the Viewport tags are extremely helpful.

The default viewport width is 980px; however, you can hard code the width of your page.  I placed the following tag in the <head> section of my MasterPage for the mobile site.

<!– meta tag for iPhone/iTouch devices –>

<meta name=”viewport” content=”width=350px” />

That worked; however, the HTML elements (buttons, selects, etc) were still far too small.  It seems that “fit to device” is more explicitly expressed with the device-width value.

<!– meta tag for iPhone/iTouch devices –>

<meta name=”viewport” content=”width=device-width” />

device-width not only fit the text to the screen, but also properly scaled the elements as well.

Excellent. ๐Ÿ™‚

I need to fully read that Safari Web Content Guide to see if there are other wonky tags for iDevice goodness. ๐Ÿ˜‰