Michael Gaigg: Über UI/UX Design

2Aug0

Silverlight Form Submission using the Enter Key

Posted by Michael Gaigg

Sounds ridiculously simple but still I need to look it up over and over again.

So here it is, documented once and forever: How to catch the Enter key (to trigger a search form submission for example).

XAML:

<TextBox x:Name="txtInputField" KeyUp="txtInputField_KeyUp" />

Code-behind (C#):

private void txtInputField_KeyUp(object sender, KeyEventArgs e)
{
   if ((e.Key == Key.Enter) && (txtInputField.Text.Length > 3)) // feel free to remove the length limit
   {
      // submit form or whatever you want to do
      this.SubmitForm();
   }
}

Note: I've added a clause so that the form is only submitted when the user has typed a minimum of 3 characters which makes sense when hitting a service for example. Feel free to remove that.

9Feb1

Add Shortcut Icon to your Webpage

Posted by Michael Gaigg

Ok, nothing earth shattering but hopefully still useful to somebody out there.

Creating Icons in the Correct Size and Format

A shortcut icon must be square in size and at least 16 x 16 pixels.
It's important to save it in .ico format. Either create a bitmap using any image editor and rename it, or use the free online tool http://www.convertico.com/.

Include it in your page

Include the following code block into your main template or master page. If you don't have that, well, then include it into every page...

<head>
	<link rel="SHORTCUT ICON" href="favicon.ico">
	<link rel="icon" href="/favicon.ico" type="image/vnd.microsoft.icon">
	<title>My Title</title>
</head>

Ah, yes, add it to the default.aspx of your Silverlight web project will do the magic as well.

Include it in your WordPress Blog

Update: Maria mentions that it is shockingly simple to include a favicon to your wordpress blog - http://wordpress.org/extend/plugins/shockingly-simple-favicon/

Show me your shortcut icon!

Send me your page with shortcut icon and if I like the icon I will bookmark it ;)

21Jan0

Including Tweets into your Webpage

Posted by Michael Gaigg

Very simple and effective. I started off researching into php libraries for twitter before I settled on a very pragmatic approach which I'd like to share here. I separated the code into smaller bits for clarity and better understanding.

Somewhere in your code include this HTML snippet (style the HTML using CSS id selectors):

<div id="twitter-container">
   <div id="twitter-container-content">
      <!-- tweet retrieval in here -->
   </div>
</div>

Copy and paste the actual PHP tweet retrieval code into the section above. Don't forget to rename the screen_name to whatever your twitter handle is ;)

print("<h2>Latest Tweets</h2>");
 
error_reporting(-1);
ini_set('display_errors', true);
 
$user = new SimpleXMLElement('http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=michaelgaigg&count=3',null,true);
 
foreach($user->status as $status){
	print("<div class=\"twitter-entry\">");
	print("<div class=\"twitter-entry-text\">".renderUrls($status->text)."</div>");
	print("</div>");
}

Add this PHP helper function (maybe you have a tools class) that will parse the tweet and detect hyperlinks which are then wrapped into the HTML A tag so that they become clickable.

function renderUrls($originalString) {
	$returnString = "";
	$stringToArray = explode(" ",$originalString);
	foreach($stringToArray as $key=>$val) {
		//$URL_Validation = ereg("^[^@ ]+@[^@ ]+\.[^@ ]+$", $val, $trashed);
		$returnString .= (substr($val,0,7) == "http://") ? "<a href='".$val."' target='_blank'>".$val."</a> " : $val." ";
	}
	return $returnString;
}

That's it, no magic!

Tagged as: , , , No Comments
19Oct0

Automatically Populate a Switch Statement for an Enum

Posted by Michael Gaigg

This one goes out to Selim - I love your 'lazy' way of programming. Here is one gem you showed me in Visual Studio:

How to automatically populate a switch statement for an enum

1.) Define your enumeration

Define an enumeration

Define an enumeration

2.) Start typing "switch"

Type "switch"

Type 'switch'

3.) Hit the [tab] key

Hit the [tab] key

Hit the 'tab' key

4.) Type the reference to your enumeration

Add reference to your enum

Add reference to your enum

5.) Hit the [Enter] key

Hit the [Enter] key

Hit the 'Enter' key

6.) Voila, all case statements are auto-populated.

Additional Tip

If two cases are identical, simply leave the first one blank (without break;) and the compiler will automatically move on to the next statement.


case FoodItem.Cake:
case Default:
// do something here that applies to Cake and default
break;

10Aug2

How to use the Google Font API

Posted by Michael Gaigg

Google fonts available

Google fonts available

If you love typography and want some new fonts for your next web project then Google Font API might be worth looking into. It's

  • easy to implement (as I will show)
  • well supported by IE, Firefox, Safari and obviously Chrome
  • open-source
  • free (I should have mentioned first huh?)

End Result

Tangerine font

Code Example

<html>
<head>
<link href='http://fonts.googleapis.com/css?family=Tangerine:regular,bold' rel='stylesheet' type='text/css'>
<style>
body {
	font-family: 'Tangerine', arial, serif;
	font-size: 2em;
}
</style>
</head>
 
<body>
This text is in <strong>Tangerine</strong>.
</body>
</html>

Implementation

The important parts in above code are to embed the font into your page through the

Link

The link element referencing the google api and your desired font family.

<link href='http://fonts.googleapis.com/css?family=Tangerine:regular,bold' rel='stylesheet' type='text/css'>

In above case I was referencing two variants delimited by a comma, the regular and the bold variant. Each variant will download an additional font and should be used only when really needed and used on the page to keep loading times as short as possible.

The variant parameter can be omitted for use of default.

<link href='http://fonts.googleapis.com/css?family=Tangerine' rel='stylesheet' type='text/css'>

One can chose to include multiple fonts by using the pipe symbol, same rules as above apply.

<link href='http://fonts.googleapis.com/css?family=Tangerine|AnotherFontName:italic' rel='stylesheet' type='text/css'>

Style

Use the font within your style sheet by simply referencing the font-family:

body { font-family: 'Tangerine', arial, serif; }

Above examples specifies fallback fonts (arial, serif) that will be displayed (depending on browser) while the font is not loaded yet or if the browser doesn't support the Google Font API (e.g. iPhone, iPad, iPod, or Android).

Oh yes, the fonts are rendered as text and therefore support CSS3 features like text-shadow and rotation.

Tools

Font previewer

Use the Font previewer to play with some style attributes, get the resulting CSS code and see how the end result will look like.

WebFont Loader

Look into the WebFont Loader for getting more control over loading the right fonts at the right time.

The WebFont Loader is a JavaScript library co-developed by Google and TypeKit that also lets you control how browsers behave while the font is still loading as well as using multiple web-font providers.

UPDATE: Chris Heilmann just posted a REALLY nice post about Controlling custom fonts with the Google WebFonts API.

What about you?

Post your link if you are using the Google Font API already. I'd like to see some really creative uses.

Are you using any other Font library?

29Mar0

jQuery: Handle Dropdown (select), Checkboxes and Radio selections

Posted by Michael Gaigg

Almost daily I work with lists, be it dropdown, checkbox or radio selections. I need to select values, submit selections, hide/show containers depending on the selection etc.

I tend to forget all these cool jQuery notations that make every programmers life easier. How nice would it be to have a little cheat sheet? So I decided to summarize my findings (and share them with you).

Obviously jQuery is powerful and gives you a multitude of possibilities so this list is neither exhaustive nor covers all possible application scenarios. Mix, match, combine and extend the samples as you wish and feel free to post your additional solutions in the comments section.

See the test page.

Dropdown

I'm using the following sample list:

<select id="ddlCategories"> 
   <option>- Select a category -</option>
   <option value="books" selected="selected">Books</option>
   <option value="videos">Videos</option>
   <option value="dvds">DVDs</option>
</select>

Get value of selected item

Pure and simple, despite what you might read in other tutorials:

alert("Selected value: " + $("#ddlCategories").val());

Change text of a particular item

Let's target item with value 'videos':

$("#ddlCategories option[value='videos']").text("Videos and tapes");

Change color of a particular item

This could be useful to show that the category is currently unavailable or a certain item is out of stock.

$("#ddlCategories option[value='videos']").css("color", "#CCC");

Get number of options

Don't forget to subtract options that don't count, e.g. the empty "- Select a category -" option.

alert("Number of options: " + ($("#ddlCategories option").length - 1));

Set a particular option

Set the option 'videos' to be the selected item.

$("#ddlCategories option[value='videos']").attr("selected", "selected");

Checkboxes

Our sample checkbox list:

<div id="chkCategoriesContainer">
	<input type="checkbox" name="chkCategories" value="none" checked="checked" />None<br/>
	<input type="checkbox" name="chkCategories" value="books" />Books<br/>
	<input type="checkbox" name="chkCategories" value="videos" />Videos<br/>
	<input type="checkbox" name="chkCategories" value="dvds" />DVDs<br/>
</div>

Check all items in the checkbox list

This could be invoked e.g. through a link named 'Check all'.

$("input[name='chkCategories']").attr("checked","checked");

Uncheck all items in the checkbox list

Same here, uncheck all, a very common requirement.

$("input[name='chkCategories']").removeAttr("checked");

Make the second item being checked

List is zero-based, so the second item is nth(1) ;)

$("input[name='chkCategories']:nth(1)").attr("checked","checked");

Show the value of each checked item (requires a container!)

In this case we simply alert the value, but we could might as well write it to another output field, container or whatever you may wish.

$('#chkCategoriesContainer :checkbox:checked').each(function() {
	alert($(this).val());
	//$('#outputField').append(', '+$(this).val());
});

Radio

Our sample list again:

<div id="rdoCategoriesContainer">
	<input type="radio" name="rdoCategories" value="none" checked="checked" />None<br/>
	<input type="radio" name="rdoCategories" value="books" />Books<br/>
	<input type="radio" name="rdoCategories" value="videos" />Videos<br/>
	<input type="radio" name="rdoCategories" value="dvds" />DVDs<br/>
</div>

Get value of checked item

alert("Selected value: " + $("input[name='rdoCategories']:checked").val());

Append item to container

The item will be added to the DOM and is available to jQuery immediately.

$('#rdoCategoriesContainer').append('<input type="radio" name="rdoCategories" value="tapes" />Audio tapes<br/>');
27Oct3

How to Disable Button on form submit in .NET

Posted by Michael Gaigg

This problem seems to be almost too obvious to be posted here but it took me quite some time to actually figure it out how to do it correctly - so I'd might just share it with you.

Disabling the submit button helps users comprehend that their action is in process and waiting for a response can be expected. It also prevents them from clicking the same action more than once which could lead to serious troubles (duplicate entries, application exceptions, etc.)

Problem

How do I disable a form submit button on a .NET page that does client-side validation?
The problem is that the button cannot simply be disabled because it would not be enabled again if the client-side validation prevents the form from being submitted.

Solution

.NET

<asp:Button runat="server" ID="btnSubmit" Text="Submit" OnClientClick="SubmitForm(this);" />

JavaScript:

function SubmitForm(source) {
ret = true;
if (typeof (Page_ClientValidate) == 'function') {
Page_ClientValidate();
ret = Page_IsValid;
}
if (ret) {
source.value = "Processing...";
source.disabled = true;
__doPostBack(source.name, "");
}
return ret;
}

7Oct1

The importance of the JavaScript parseInt radix

Posted by Michael Gaigg

Problem:

Just recently I had to implement an HTML form that allows users to enter percentage values. Like every good programmer I added client-side validation to check that the input values are between 0 and 100.

Using the JavaScript function parseInt(txtValue) with txtValue being the value of the input field our tester was able to submit the form with a value of 0137.

My first reaction was to restrict the maxlength attribute of the input field to 3 characters only. Even though this is a good and recommended practise there was clearly something else wrong.

Explanation:

The parseInt() function parses a string and returns an integer. The signature is parseInt(string, radix) with

  • string (required) being the string to be parsed, and
  • radix (optional) a number (from 2 to 36) that represents the numeral system to be used

If the radix parameter is omitted, JavaScript assumes the following:

  • If the string begins with “0x”, the radix is 16 (hexadecimal)
  • If the string begins with “0”, the radix is 8 (octal)
  • If the string begins with any other value, the radix is 10 (decimal)

Solution:

So, what happened? Because I forgot to specify the radix and our QA tester tried the (however unlikely) case of 0137 JavaScript assumed it was an octal number and returned a value of 95. Lesson learned: Always specify the radix (if it decimal set it to 10 ;) !!!!

PS.: Only the first number in the string is returned!
PPS.: Leading and trailing spaces are allowed.
PPPS.: If the first character cannot be converted to a number, parseInt() returns NaN.