Archive for the ‘ JavaScript’ Category

Fight Score Single Page UI App

I asked a question on Twitter last week about jQuery and async calls (thanks @jeefy & @codepo8) – a few folks asked me to post the code I was working on so here it goes.

The app is an HTML page for scoring boxing and MMA fights.

You can play with the UI here : http://koscience.com/apps/scorecard/

This is a mile stone of code samples I’ve posted recently on Dynamic jQuery Accordions and Event Handler Delegation for Dynamic Content.

scorecard-1

The events represented in the application’s UI are data driven by the retrieved JSON file (sample data below)


data.json


[
    {
        "bluefighter"       : "Fighter 1",
        "blueimage"         : "images/silhouette.jpg",
        "redfighter"        : "Fighter 2",
        "redimage"          : "images/silhouette.jpg",
        "numberofrounds"    : "10"
    },
    {
        "bluefighter"       : "Fighter 3",
        "blueimage"         : "images/silhouette.jpg",
        "redfighter"        : "Fighter 4",
        "redimage"          : "images/silhouette.jpg",
        "numberofrounds"    : "3"
    },
    {
        "bluefighter"       : "Fighter 5",
        "blueimage"         : "images/silhouette.jpg",
        "redfighter"        : "Fighter 6",
        "redimage"          : "images/silhouette.jpg",
        "numberofrounds"    : "5"
    },
    {
        "bluefighter"       : "Fighter 7",
        "blueimage"         : "images/silhouette.jpg",
        "redfighter"        : "Fighter 8",
        "redimage"          : "images/silhouette.jpg",
        "numberofrounds"    : "12"
    }
]

You’ll note that the number of bouts in the event are not determined until run time.

Also, for each bout, the number of rounds is not fixed. Each is determined by an entry in the JSON data.

Since each bout will have a VARIABLE number of inputs and outputs, if you think about the mechanics of accomplishing this, it’s an interesting HTML issue.

There are lots of other, perhaps more elegant ways I might have done this (whenever I post code someone comments to tell me I suck :) )

I didn’t use MVC, Event Delegation, or an Object Oriented Data Model. Each of those that I considered just didn’t seem to offer the value in return for the added abstraction or complexity.

(I used to do some work for the SIG Sauer Firearms Academy where we used the acronym SIG = Simple Is Good !)

So I took the simple route. The loop that iterates through the JSON data dynamically adds each content section and since I’m not using event delegation, each “bout” (accordion tab) gets it’s own version of the event handling code to score the bout.

Since the number of bouts is relatively small (less than 15) the performance hit won’t ever be an issue, but if we were dealing with a large number of sections we would need to use delegation of some sort to attach a single event handler at the containing element or document level to avoid unnecessarily duplicating code by hooking the click event for every object / button.


index.html


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fight Card</title>
<link rel="stylesheet"
 href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="css/style.css">
<style>
	/* IE has layout problems when sorting accordion items  */
	.group { zoom: 1 }
</style>

<script>

//-----------------------------------------------------------------------+
// addBout() - Add a single node to the accordion
//-----------------------------------------------------------------------+

function addBout(bout, key){

//-----------------------------------------------------------------------+
// Build the display element for the the scoring display based on the 
// number of rounds for this bout.
//-----------------------------------------------------------------------+
var round_numbers = "";
var round_scores = "";
var round_totals = "";
for (var i=0; i < bout.numberofrounds; i++)
{
	round_numbers += "<td id='roundTitle_" + (key+1) + "_" + (i+1) 
				   + "'>Round #" + (i+1) + "</td>";
	round_scores  += "<td id='bout_" +  (key+1) + "_round_" + (i+1) 
				   + "_roundbox'><span id='bout_" + (key+1) + "_round_" 
				   + (i+1) +  "_blueScore'>00</span>-<span id='bout_" 
				   + (key+1) + "_round_" + (i+1) 
				   +  "_redScore'>00</span></td>";

	round_totals  += "<td id='bout_" +  (key+1) + "_round_" + (i+1) 
				   + "_totalbox'><span id='bout_" + (key+1) + "_round_" 
				   + (i+1) +  "_blueTotal'>00</span>-<span id='bout_" 
				   + (key+1) + "_round_" + (i+1) 
				   +  "_redTotal'>00</span></td>";
}

//-----------------------------------------------------------------------+
// Build the display element for the rest of the current bout.
//-----------------------------------------------------------------------+
var bout =
	"<div id=\"bout_" + (key+1) + "\" class=\"group\">" +
		"<span class=\"handle\"> " +
			"<div class=\"table\">" +
				"<div class=\"row\">" +
					"<span class=\"cell width33pct align-left\">" +
						"<strong>" + bout.bluefighter + "</strong>" +
					"</span>" +
					"<span class=\"cell align-center valign-middle\">" +
						"vs." +
					"</span>" +
					"<span class=\"cell width33pct align-right\">" +
					"<strong>" + bout.redfighter + "</strong>" +
					"</span>" +
				"</div>" +
			"</div>" +
		"</span>" +
		"<div>" +
			"<div class=\"table\">" +
				"<div class=\"row\">" +
					"<span class=\"cell width150 align-center\">" +
						"<img src=\"" + bout.blueimage 
						+ "\" alt=\"\" style='border:2px solid blue'>"
						+ "<br />" +
					"</span>" +
					"<span id=\"test\" "  +
					"class=\"cell align-center valign-middle\">" +
						"<h2>" +
						"<span id='roundLabel_" + (key+1) + 
						"'>Round</span><br />" +
						"<span id=\"current_round_" + (key+1) + 
						"\">1</span><br />" +
						"<input type='number' id='blueRoundScore_" + 
						(key+1) + "' size='2' max='10' min='0' " +
						"value='10' " +
						"style='border:2px solid blue'>" +
						"<input type='number' id='redRoundScore_"  + 
						(key+1) + "' size='2' max='10' min='0' " +
						"value='10' style='border:2px solid red'>" +
						"<br /><br />" +
						"<button id='btnScore_" + (key+1)  + 
						"' class='score_button'>Score</button>" +
						"<span id='boutResult_" + (key+1)+ "' " +
						"class='boutResultClass'></span>" +
						"</h2>" +
					"</span>" +
					"<span class=\"cell width150 align-center\">" +
						"<img src=\"" + bout.redimage + "\" alt=\"\" " +
						"style='border:2px solid red'>" +
					"</span>" +
				"</div>" +
			"</div>" +
			"<div align=\"center\">" +
				"<table>" +
					"<tr>" +
						round_numbers +
					"</tr>" +
					"<tr>" +
						round_scores +
					"</tr>" +
					"<tr>" +
						round_totals +
					"</tr>" +
				"</table>" +
			"</div>" +
		"</div>" +
	"</div>";
return bout;
}

//--------------------------------------------------------------------------+
// DOM READY()
//--------------------------------------------------------------------------+
$(function() {
	//----------------------------------------------------------------------+
	// Wire up the accordion div, specify the header/handle and make 
	// the sections sortable.
	//----------------------------------------------------------------------+
	$( "#accordion" )
			.accordion({
				header: "> .group > .handle",
				heightStyle: "content"
			})
			.sortable({
				axis: "y",
				handle: ".handle",
				stop: function( event, ui ) {
					// IE doesn't register the blur event when sorting
					// so trigger focusout handler to remove .ui-state-focus
					ui.item.children(".handle").triggerHandler("focusout");
				}
			});

	//----------------------------------------------------------------------+
	// Fetch the JSON configuration file and use it to build the 
	// accordion sections
	//----------------------------------------------------------------------+
	$.getJSON("data/event.json", function (data) {
		$.each(data, function (key, val) {
			$("#accordion").append(addBout(val, key)).accordion("refresh");

			//--------------------------------------------------------------+
			// For each bout - dynamically bind the score button event 
			// handler to this dynamic method
			//--------------------------------------------------------------+
			var BlueTotal = 0;
			var RedTotal = 0;
			var BoutNumber = (key+1);
			$( "#boutResult_"+(BoutNumber) ).hide();
			$( "#btnScore_"+(BoutNumber) ).click(function() {
			// Get the current round number.
			var currentRound = 0;
			currentRound = $("#current_round_" + (BoutNumber)).text();

			//----------------------------------------------------------+
			// Fetch the score for the current round and post to 
			// scoring table
			//----------------------------------------------------------+
			var BlueScoreThisRound =  $("#blueRoundScore_" + 
				                         BoutNumber).val();
			var RedScoreThisRound =   $("#redRoundScore_" + 
				                         BoutNumber).val();
			$("#bout_" + (BoutNumber) + "_round_" + currentRound + 
			   "_blueScore").text(BlueScoreThisRound);
			$("#bout_" + (BoutNumber) + "_round_" + currentRound + 
				"_redScore").text(RedScoreThisRound);
			// If it's the FIRST round.
			if (currentRound == 1) {
				$("#bout_" + (BoutNumber) + "_round_" + currentRound + 
				  "_blueTotal").text(BlueScoreThisRound);
				$("#bout_" + (BoutNumber) + "_round_" + currentRound + 
					"_redTotal").text(RedScoreThisRound);
				BlueTotal = BlueScoreThisRound;
				RedTotal = RedScoreThisRound;
			}
			// All except the first round.
			else {

				 BlueTotal = parseInt($("#bout_" + (BoutNumber) + 
				 	"_round_" + (currentRound-1)  + 
				 	"_blueTotal").text());
				 BlueTotal += parseInt(BlueScoreThisRound);
				 $("#bout_" + (BoutNumber) + 
				 	"_round_" + (currentRound)  + 
				 	"_blueTotal").text(BlueTotal);

				 RedTotal = parseInt($("#bout_" + (BoutNumber) + 
				 	"_round_" + (currentRound-1)  + 
				 	"_redTotal").text());
				 RedTotal += parseInt(RedScoreThisRound);
				 $("#bout_" + (BoutNumber) + "_round_" + 
				 	(currentRound)  + "_redTotal").text(RedTotal);
			}

			// Blue wins the round.
			if (BlueScoreThisRound < RedScoreThisRound) {
			  $("#bout_" + (BoutNumber) + "_round_" + currentRound + 
			  	"_roundbox").css("border", "2px solid blue");
			}
			// Red wins the round.
			else if (BlueScoreThisRound > RedScoreThisRound) {
				$("#bout_" + (BoutNumber) + "_round_" + currentRound + 
					"_roundbox").css("border", "2px solid red");
			}
			// Round is a draw
			else if (BlueScoreThisRound == RedScoreThisRound) {
				$("#bout_" + (BoutNumber) + "_round_" + currentRound + 
					"_roundbox").css("border", "2px solid green");
			}

			// Who's winning the fight after this round ?
			if(RedTotal == BlueTotal) {
				$("#roundTitle_" + (BoutNumber) + "_" + 
					currentRound).css("border", "2px solid green");
				$("#bout_" + (BoutNumber) + "_round_" + 
					currentRound + 
					"_totalbox").css("border", "2px solid green");
			}
			if(BlueTotal < RedTotal) {
			   $("#roundTitle_" + (BoutNumber) + "_" + 
			   	currentRound).css("border", "2px solid red");
			   $("#bout_" + (BoutNumber) + "_round_" + 
			   	currentRound + "_totalbox").css("border", "2px solid red");
			}
			if (BlueTotal > RedTotal) {
				$("#roundTitle_" + (BoutNumber) + "_" + 
					currentRound).css("border", "2px solid blue");
				$("#bout_" + (BoutNumber) + "_round_" + 
					currentRound + 
					"_totalbox").css("border", "2px solid blue");
			}


			//----------------------------------------------------------+
			// Reset current round scores t 10-10, hide button if all 
			// rounds scored
			//----------------------------------------------------------+
			$("#blueRoundScore_" + BoutNumber).val(10);
			$("#redRoundScore_" + BoutNumber).val(10);
			currentRound++;
			// The fight is over.
			if (currentRound > val.numberofrounds) {
				$("#blueRoundScore_" + BoutNumber).val(BlueTotal);
				$("#blueRoundScore_" + BoutNumber).prop('disabled', true);
				$("#redRoundScore_" + BoutNumber).val(RedTotal);
				$("#redRoundScore_" + BoutNumber).prop('disabled', true);
				$( "#btnScore_"+(BoutNumber)).hide();
				if(BlueTotal == RedTotal) {
					$( "#boutResult_"+(BoutNumber) ).text("<<<  Draw  >>>");
				}
				else if (BlueTotal > RedTotal) {
					$( "#boutResult_"+(BoutNumber) ).html("&larr; WINNER");
					$( "#boutResult_"+
						(BoutNumber) ).css("background-color", "blue");
					$( "#boutResult_"+(BoutNumber) ).css("color", "white");
				}
				else if (RedTotal > BlueTotal) {
					$( "#boutResult_"+(BoutNumber) ).html("WINNER &rarr;");
					$( "#boutResult_"+
						(BoutNumber) ).css("background-color", "red");
					$( "#boutResult_"+(BoutNumber) ).css("color", "white");
				}

				$( "#roundLabel_"+(BoutNumber) ).text("Fight");
				$( "#current_round_"+(BoutNumber) ).text("Complete");
				$( "#boutResult_"+(BoutNumber) ).show();

			}
			// On to another round.
			else {
				$("#current_round_" + (key+1)).text(currentRound);
			}
			});
		});

	});

});

</script>
</head>

<body>
<div id="main-container" class="main-container">
	<div id="accordion">
	<!-- Bouts will be inserted here -->
	</div>


</div>
</body>
</html>


style.css


body {
	font-family: "Trebuchet MS","Helvetica","Arial","Verdana","sans-serif";
	font-size: 62.5%;
    background: url('../images/background.gif') repeat;
}

td {
    text-align: center;
    vertical-align: middle;
    border: 1px solid black;
    width: 90px;
}

input {
    text-align: center;
}


.main-container {
    width: 96%;
    max-width: 960px;
    min-width: 300px;
    height: 100px;
    position: absolute;
    top:20px;
    left: 0;
    right: 0;
    margin: auto;
}

/*---------------------------------------*/
/*   Styles for table like formatting.   */
/*---------------------------------------*/
.table {
    display: table;
    width: 100%;
}
.row {
    display: table-row;
}
.cell {
    display: table-cell;
}

/*---------------------------------------*/
/*   Styles for score area.              */
/*---------------------------------------*/

.score_box {
    border:2px solid black;
    padding: 5px;
}

.score_button {
    width: 130px;
    height: 40px;
}

.boutResultClass {
    border: 2px solid black;
    background-color: yellow;
    padding-left: 20px;
    padding-right: 20px;
    padding-top: 10px;
    padding-bottom: 10px;
}

/*---------------------------------------*/
/*   Styles for width specification.     */
/*---------------------------------------*/
.width150 {
    width: 150px;
}

.width33pct {
    width: 33%;
}

.width34pct {
    width: 34%;
}

.width100pct {
    width: 100%;
}

/*---------------------------------------*/
/*   Styles for various alignments.      */
/*---------------------------------------*/
.align-right {
    text-align: right;
}
.align-left {
    text-align: left;
}
.align-center {
    text-align: center;
}

.valign-middle {
    vertical-align: middle;
}

/*-------------------------------------------*/
/*   Style overrides for jQuery accordion.   */
/*-------------------------------------------*/
.ui-state-default{
    background-color: #3173a5;
    background-image: none;
}
.ui-accordion-header {
    background-color: #333333;
    color:  #BDC3C7;
    font-size: 16;
}

.ui-accordion-header.ui-state-active {
    background-color: #BDC3C7;
    color: #333333;
    font-size: 16;
}

You can download a .zip file without the funky source code formatting that my blog requires [ HERE ]


So what’s next ?

Next I’ll create services so that users can all score an event in real time, collaboratively while the event is happening live.

After I create the services and update the client to send scores, I’ll build iOS, Android & Windows clients !

jQuery Accordion and Dynamic Runtime Population

As I mentioned in my last post I’m playing with this idea of building a scoring application for boxing / mma events.

I want it to be a single page web application that scales to fit phones, tablets, etc.

An event contains a number of “bouts” and each bout will be a section in a jQuery UI Accordion control.

However, as is often the case, there are a couple of real world conditions that I couldn’t find documentation of sample to demonstrate.

1.) Event event can have a different number bouts.

This means that the accordion sections have to be dynamically built at runtime in the html page.

2.) The order of the events can change right up to the event time.

This means that the USER needs to be able to change the visual sequence of the bouts.

3.) The click-able header needs to be multiple elements.

All the demos I found assumed the headers were simple H3 elements.

You can play with a working version by clicking the image below.

Note that you can not only open and close the “bouts” but you can re-order them using drag-n-drop on the title bars.

– - – THIS IS A UI PROTOTYPE – - –

FightCard- 001

Built this way I can now add the AJAX logix fo recieve a JSON package that contains the event detail and use that data to populate the event.

Here is the code as it exists so far.

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Fight Card</title>
<link rel="stylesheet"
 href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<link rel="stylesheet" href="css/style.css">
<style>
    /* IE has layout problems when sorting  */
    .group { zoom: 1 }
</style>

<script>

//-----------------------------------------------------------+
// addBout() - Add a single node to the accordian
// TODO: add JSON object as input parameter and build the
//       bout with that data,
//-----------------------------------------------------------+
function addBout(){
    var bout =
        "<div class=\"group\">" +
            "<span class=\"handle\"> " +
                "<div class=\"table\">" +
                    "<div class=\"row\">" +
                        "<span class=\"cell width33pct align-left\">" +
                            "<strong>Blue Fighter TBD</strong>" +
                        "</span>" +
                        "<span class=\"cell align-center valign-middle\">" +
                            "vs." +
                        "</span>" +
                        "<span class=\"cell width33pct align-right\">" +
                            "<strong>Red Fighter TBD</strong>"+
                        "</span>" +
                    "</div>" +
                "</div>" +
            "</span>" +
            "<div>" +
                "<div class=\"table\">" +
                    "<div class=\"row\">" +
                        "<span class=\"cell width150 align-center\">" +
                            "<img src=\"images/silhouette.jpg\" alt=\"\">" +
                        "</span>" +
                        "<span class=\"cell align-center valign-middle\">" +
                            "Round<br />0" +
                        "</span>" +
                        "<span class=\"cell width150 align-center\">" +
                            "<img src=\"images/silhouette.jpg\" alt=\"\">" +
                        "</span>" +
                    "</div>" +
                "</div>" +
                "<span>" +
                "Mauris mauris ante, blandit et, ultrices a, suscipit , " +
                "quam. Integerut neque. <br /> Vivamus nisi metus molestie" +
                " vel, gravida in, condimentum sit amet, nunc. Nam a nibh." +
                "accordion .ui- iconDonec suscipit eros. Nam mi. Proin " +
                " viverra leo ut odio. Curabitur malesuada. Vestibulum a " +
                "velit eu ante scelerisque vulputate." +
                "</span>" +
            "</div>" +
        "</div>";
    return bout;
}

$(function() {

    $( "#accordion" )
            .accordion({
                header: "> .group > .handle",
                heightStyle: "content"
            })
            .sortable({
                axis: "y",
                handle: ".handle",
                stop: function( event, ui ) {
                    // IE doesn't register the blur event when sorting
                    // so trigger focusout handler to remove .ui-state-focus
                    ui.item.children(".handle").triggerHandler("focusout");
                }
            });

    //-----------------------------------------------------------+
    // This for loop is just for testing.
    // The real app will iterate a JSON collection and send
    // each bout node to the addBout function for insertion
    // into the accordion
    //-----------------------------------------------------------+
    for (var i=0;i<5;i++) {
    $("#accordion").append(addBout()).accordion("refresh");
    }
});
</script>

</head>

<body>

<div id="main-container" class="main-container">
    <div id="accordion">
    <!-- Bouts will be inserted here -->
    </div>
</div>

</body>
</html>

And the CSS

body {
   font-family: "Trebuchet MS","Helvetica","Arial","Verdana","sans-serif";
   font-size: 62.5%;
   background: url('../images/background.gif') repeat;
}

.main-container {
    width: 96%;
    max-width: 960px;
    min-width: 300px;
    height: 100px;
    position: absolute;
    top:20px;
    left: 0;
    right: 0;
    margin: auto;
}

/*---------------------------------------*/
/*   Styles for table like formatting.   */
/*---------------------------------------*/
.table {
    display: table;
    width: 100%;
}
.row {
    display: table-row;
}
.cell {
    display: table-cell;
}

/*---------------------------------------*/
/*   Styles for width specification.     */
/*---------------------------------------*/
.width150 {
    width: 150px;
}

.width33pct {
    width: 33%;
}

.width34pct {
    width: 34%;
}

/*---------------------------------------*/
/*   Styles for various alignments.      */
/*---------------------------------------*/
.align-right {
    text-align: right;
}
.align-left {
    text-align: left;
}
.align-center {
    text-align: center;
}

.valign-middle {
    vertical-align: middle;
}

/*-------------------------------------------*/
/*   Style overrides for jQuery accordion.   */
/*-------------------------------------------*/
.ui-state-default{
    background-color: #3173a5;
    background-image: none;body {
	font-family: "Trebuchet MS","Helvetica","Arial","Verdana","sans-serif";
	font-size: 62.5%;
    background: url('../images/background.gif') repeat;
}

.main-container {
    width: 96%;
    max-width: 960px;
    min-width: 300px;
    height: 100px;
    position: absolute;
    top:20px;
    left: 0;
    right: 0;
    margin: auto;
}

/*---------------------------------------*/
/*   Styles for table like formatting.   */
/*---------------------------------------*/
.table {
    display: table;
    width: 100%;
}
.row {
    display: table-row;
}
.cell {
    display: table-cell;
}

/*---------------------------------------*/
/*   Styles for width specification.     */
/*---------------------------------------*/
.width150 {
    width: 150px;
}

.width33pct {
    width: 33%;
}

.width34pct {
    width: 34%;
}

/*---------------------------------------*/
/*   Styles for various alignments.      */
/*---------------------------------------*/
.align-right {
    text-align: right;
}
.align-left {
    text-align: left;
}
.align-center {
    text-align: center;
}

.valign-middle {
    vertical-align: middle;
}

/*-------------------------------------------*/
/*   Style overrides for jQuery accordion.   */
/*-------------------------------------------*/
.ui-state-default{
    background-color: #3173a5;
    background-image: none;
}
.ui-accordion-header {
    background-color: #333333;
    color:  #BDC3C7;
    font-size: 16;
}

.ui-accordion-header.ui-state-active {
    background-color: #BDC3C7;
    color: #333333;
    font-size: 16;
}

}
.ui-accordion-header {
    background-color: #333333;
    color:  #BDC3C7;
    font-size: 16;
}

.ui-accordion-header.ui-state-active {
    background-color: #BDC3C7;
    color: #333333;
    font-size: 16;
}

A First In – First Out JavaScript Queue

I recently started building a demo to highlight application design practices that leverage HTML5 features to deliver an “app” experience. The model for this particular demo was that of a video portal and the first step was to to make independent XmlHttpRequest calls to fetch the videos on demand.

Here is where we want to ed up with this app.

  1. The content gets updated with LINKS to new videos.
  2. The user selects videos to be downloaded.
  3. The videos are downloaded in the background without effecting the user interface performance.
  4. The user can select as many videos as they want for download and they will be queued up.
  5. The videos will be stored locally for use later.
  6. The user will be warned if they try to close the app when files are still downloading.

I posted a simple demo of using Web Workers here.

In this post we’ll look at how to stack all of the user’s video download requests in a JavaScript queue object. This is necessary because the user can click on links to videos faster than they can be downloaded. In our previous example if the user clicks on a video to download and then clicks on a different video before the first one has finished downloading – that first video download is simply abandoned and the second video download begins. We need to queue them so that all the videos selected will be asynchronously downloaded in the background.

Lets first look at a simple JavaScript Queue – then we will look at the better way to do solve the problem.

In JavaScript the array is a pretty flexible construct.

To create an instance of an array :


var queue = new Array();

An array in JavaScript can contain any type of data (more on this in a minute) and each item in an array does not have to be of the same type as the others.

There are two sets of ways to add and remove items from an array.

One set works against the beginning of an array and the other works against the bottom.


shift() – Removes the first element of an array, and returns that element
unshift() – Adds new elements to the beginning of an array, and returns the new length


pop() – Removes the last element of an array, and returns that element
push() – Adds new elements to the end of an array, and returns the new length


In order to process a FiFo (First In – First Out) queue, we’ll need to use one of each.

We’ll use push() to add an additional item to the top of the queue and we’ll use shift() to retrieve (and remove)  an item from the bottom of the queue and move all the remaining items down to fill in for the removed item.

Given the following HTML :



<!doctype html>  
<html>  
  <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
    <script src="js/code.js"></script>
    <script type="text/javascript">

      function doStackAdd() {
        var inputValue = document.getElementById('txtInput').value;
        if(inputValue) {
          stackAdd(inputValue);
          document.getElementById('txtInput').value = "";
        }
      }
		
      function doStackGet() {
        var returnValue = stackGet();
        document.getElementById('stackResult').innerHTML = returnValue;
      }
    </script>   
    <title>JavaScript FIFO - Worker</title>  
  </head>  
  <body>
    <center>
      <h3>JavaScript Simple FiFo Queue</h3>
      <div id="mainDiv" style="background-color: silver; 
                        width:410px; padding: 20px; text-align: left;">
        Input : <input type="text" id="txtInput" value="">
        <button onclick="doStackAdd()">Add to Stack</button> 
        <br /><br />
        <button onclick="doStackGet()">Get from Stack</button> >>>
        &nbsp;&nbsp;
        <span id="stackResult"></span>
      </div>	           
     </center>
   </body>  
</html>

Which renders the following page…


Note that the button click() event handlers call JavaScript functions defined in the code.js file.


//---------------------------------------------------------------------+
// Code for SIMPLE FiFo Queue (Stack)
//---------------------------------------------------------------------+
var queue = new Array();

function stackAdd(valueToAdd) {

	queue.push(valueToAdd);
}

function stackGet() {
	var retrievedQueueValue = queue.shift();
	if(retrievedQueueValue) {
	   return retrievedQueueValue;
    }
    else {
	   return "Queue is empty.";
	}
}

So, when we add a few items to the queue by entering text and clicking the “add” button…….





We then have a few (three) items on the stack.

Now if we start clicking on he “Get from Stack” button we can see that the items we entered come off the stack in the order we put them on.





When the queue is empty, we report that the queue is empty.



This works, but only allows us to push “single” values onto the stack.

Remember that our use-case for this is to put videos that we want to download into a queue.

Practically speaking, we will want to attach some information to the video to be downloaded. AT a minimum a name for the video, maybe a description.

At first you may consider a JavaScript Hash, also known as an associative array.

But this data structure is not very well suited for this type of usage.

With an Associative Array you store Key / Value Pairs. The key is not really part of the data, it’s the index into that element of an array. As such you use the value of the key to retrieve the item you want.

It makes more sense for us to define a custom type ( a video for download type) and then work with an array of object of that type.

So for the given markup….



<!doctype html>  
<html>  
  <head>  
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />  
    <script src="js/code.js"></script>
    <script type="text/javascript">
      
      function doObjArrayAdd() {
        var inputName = document.getElementById('txtInputName').value;
        var inputURL = document.getElementById('txtInputURL').value;
        var inputDesc = document.getElementById('txtInputDesc').value;	
 
        if(inputName && inputURL && inputDesc) {
          objArrayAdd(inputName, inputURL, inputDesc);
          document.getElementById('txtInputName').value = "";
          document.getElementById('txtInputURL').value = "";
          document.getElementById('txtInputDesc').value = "";
         }
       }

      function doObjArrayGet() {
        var returnValue = objArrayGet();
        document.getElementById('vidoObjectResult').innerHTML = returnValue;
      }
    </script>   
    <title>JavaScript FIFO - Worker</title>  
  </head>  
  <body>
    <center>
      <h3>JavaScript FiFo Queue - Object Array</h3>
      <div id="mainDiv" style="background-color: silver; 
                        width:500px; padding: 20px; text-align: left;">
        Name : 
        <input type="text" id="txtInputName" value=""  style="width:300px;">
        <br />
        &nbsp;&nbsp;&nbsp;URL : 
        <input type="text" id="txtInputURL" value="" style="width:300px;">
        <br /><br />
        Desctiption :  
        <textarea id="txtInputDesc" rows="8" cols="68"></textarea> 
        <button onclick="doObjArrayAdd()">Add to Collection</button> 
        <br /><br />
        <button onclick="doObjArrayGet()">Get from Collection</button>
        <br /><br />
        <span id="vidoObjectResult">&nbsp;</span>
      </div>		           
     </center>
   </body>  
</html>

Then in our button click() event handler we will define our custom type and create an array of object instances from our user defined type.


//---------------------------------------------------------------------+
// Code for Object  FiFo Queue 
//---------------------------------------------------------------------+
function VideoObject(name, url, desc)
{
this.name = name;
this.url = url;
this.desc = desc;
} 

var VideoObjectArray = new Array();

function objArrayAdd(nameToAdd, urlToAdd, descToAdd) {
	
   newVideo = new VideoObject(nameToAdd, urlToAdd, descToAdd);  
   VideoObjectArray.push(newVideo);
}

function objArrayGet() {
   var retrievedVideoObject = new VideoObject();
   retrievedVideoObject = VideoObjectArray.shift(); 
	
   if(retrievedVideoObject) {
      return retrievedVideoObject.name + ":" + 
             retrievedVideoObject.url + ":" + retrievedVideoObject.desc;
   }
   else {
      return "VideoObjectArray is empty.";
   }
}

Note that when we use shift() to retrieve an item from our array we can’t don’t pass that object instance to the calling method. It would work here in this example, but when we move this code to a Web Worker, this code will be called via a Web Worker message and the calling code will not have access to the type defined in the referenced .js file.

Now when we run the page and add an item to the queue…..



And then click on the button to retrieve the object….



So there we have an implemented FiFo Object Queue in JavaScript.

What’s next ?

  • Store the videos locally.
  • Implement AppCache to work off line
  • Move the downloading into a web worker
  • Update the UI to destinguish between, available, downloading, and downloaded videos
  • Prevent the user from closing the app while files are still downloading.


** You can download the source code for the above example HERE.


Installing NODE.js on Ubuntu Linux.

I sometimes describe dynamic web applications (PHP or ASP.NET) as 1 ½ tier applications.

Really all the application logic runs on one server (sometimes the database lives on a separate server with some logic in Stored Procedures) and the browser is the “client”. But in those applications the “client” is really not a client in the client server sense. It’s the TERMINAL.

The more we federate logic in our web applications to the user’s machine (inside or outside of the browser) the more we take load responsibility away from our server infrastructure.

I think NODE.js is a great potential alternative for the server side piece of a real web based client / server scenario.

However, in searching the web you find lots of posts about how to install NODE.js that are pretty intimidating.

I found it very easy to set up on Ubuntu so I thought I’d share the steps in case anyone would find them useful.

You can do the install on Ubuntu 11.10 using the Synaptic Package Manager.

On the Ubuntu Unity tool bar, click on the “Dash home” icon at the top of the bar.

Start typing “Synaptic” to search for the package manager and when it appears, click to fire up the Synaptic Package Manager.

In the Synaptic Package Manager enter node.js into the package search box.

As you see above, select NODE.js (I also selected the developer and debug packages) and then click on the “Apply” button.

When you’re done the Package Manager Dialog should look something like the one above.

Then open up text editor (in the image below, I’m using Geany)

Enter just the seven lines of code shown above which will serve as a test to confirm that NODE.js is installed correctly.



var http = require('http');

http.createServer(function (req, res) {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('NOTICE : Node.js is Running !!!\n');
}).listen(8100, "127.0.0.1");

console.log('Server running at http://127.0.0.1:8100/');


Now save the file where you want to execute it from.

I saved mine in the default directory for web content (/var/www/hello_node.js)

Once you have saved the file, open up a terminal window and go to the directory where you saved the file.

(Type “cd /var/www” and hit return.)

Then list the directory to make sure you newly created file is there.

(Type “ls” and then hit return.

Assuming all has gone well up to this point, type in the following command and hit return.

“node hello_node.js”

You should see the “Server Running” console trace message from our hello_node.js file as you see in the screenshot below.

Now open your browser (GetfireFox.com) and navigate to http://localhost:8100

8100 is the port we told our little app to listen on.

And there you go. We’re ready to start digging in to NODE.js

I’ll try to add instructions for Mac and Windows in the near future.


Using ENUM in JavaScript – Almost.

Web Standards based app building means more logic in our client side code (HTML and JavaScript).

When you’re moving from a language like C++, Java or C# that means adapting to find alternatives to language constructs in those languages.

So, this will be the first in an ongoing series on constructs in JavaScript.

I’m building a workout timer application and I’m doing in the 3 stages.

  1. A standard, connected, web page with all logic on the client but no “new wave” features.
  2. An enhanced version with Off Line, Local Storage, and other HTML5 goodness.
  3. An enhanced experienced for “when connected” times.

I’ve been writing C# for more than a decade and, though I’m happy with other server-side dialects, I do love C#.

One of the constructs that I ran in to is Enumerated Types.

There is no actual ENUM type in JavaScript but there are was that we can get close.

One this to note is that we don’t get all the benefits that we get using the ENUM type in Java or C#. We don’t get type safety, for example.

We can fake enums in a few ways. First we can declare a pseudo-enum as a collection of dictionary pairs and then access the entries using a convenient dot syntax.

Like this – variable.entry


var Mode = { "NONE": 0, 
             "PAUSED": 1, 
             "WORK": 2, 
             "REST": 3, 
             "HIGH": 4, 
             "LOW": 5, 
             "LOW": 6 };

var TimerState = Mode.NONE;

We can also make our pseudo-enum immutable by freezing the object when the number of options for the emun will or should never be changed.


var DaysOfTheWeek = { "Sunday":1, 
                      "Monday":2, 
                      "Tuesday":3, 
                      "Wednesday":4, 
                      "Thursday":5, 
                      "Friday":6, 
                      "Saturday":7				 
                    }
Object.freeze(DaysOfTheWeek);

The Object.Freeze method was added to JavaScript in version 1.8.5 ( Read HERE )

Since JavaScript is loosely types, we could even make our pseudo-enum a collection of Object like this.


var SIZE = {
  SMALL : {value: 0, name: "Small", code: "S"}, 
  MEDIUM: {value: 1, name: "Medium", code: "M"}, 
  LARGE : {value: 2, name: "Large", code: "L"}
};

Since we don’t get type safety I could still assign any value that I wanted to a variable that I indent to contain only one of the enumerated values.

Example:


var DaysOfTheWeek = { "Sunday":1, 
                      "Monday":2, 
                      "Tuesday":3, 
                      "Wednesday":4, 
                      "Thursday":5, 
                      "Friday":6, 
                      "Saturday":7				 
 }
 
 var myDay = DaysOfTheWeek.Friday;
 
 myDay = 99;
 
 myDay = "JunkData";

None of these would cause a run-time error but the last 2 would break the semantic intent of the myDay variable.

We just need to write GOOD code.

I still find great value in using these pseudo-enums. In my particular application I’m writing some pretty complex JavaScript code to implement an interval time with various states. The use of this technique not only make the code easier to understand but most JavaScript aware editors that support auto-suggest will reflect on the pseudo-enum and provide assistance when using them.


Selecting and Installing JavaScript Developer Tools for Linux

Choosing an editor or IDE for development is a personal thing, like choosing a car. What is a perfect ride for one person offers no interest at all to another. Personally, I was never happy with only one car and usually want different ones in the garage so that I can choose the one that most closely matches my mood or the kind of driving that I need to do.

Some folks like the help and tooling of a fully integrated environment like Visual Studio. Others like the hardcore elitism of EMACS or Vi. I’m a pragmatist, I like tools that just help me get the job done.

For right now I’ll focus on tools for the client side of web development. Here’s what I’ve chosen. All of these tools are free. There is one commercial application that I’ll add at the end because I think it’s worth the money.

jEdit is a good general programmer’s editor with syntax highlighting support and, though it’s feature rich, it doesn’t get in your way while you’re writing code.

jEdit is written in Java and so it runs on Linux. Mac and Windows. I especially like the rich plug-in repository where i can get and add all kinds of specific features that I’m interested in.

You can install jEdit via the Ubuntu Software Center.

And you can get plug-ins here – http://plugins.jedit.org/

Though jEdit is a great general purpose programmer’s editor, I tend to like something with HTML specific features when doing HTML work.

Though there are many HTML editors available for Linux and most of them are free, most of them lack any specific support for HTML5.

Read the rest of this entry »

Simulating Function Overloading in JavaScript.

I sometimes hear people rant about JavaScript and how it’s not a modern language with modern constructs. When comes to Object Orientation, you can write Object “Oriented” code in any language. We wrote Objected Oriented code in straight “C” 20 years ago. Though the language didn’t natively support advanced OO constructs.

JavaScript a script programming language with its own idea about Object Orientation.

While JavaScript’s current implementation does not support function overloading, we can simulate it using the loose type system included in JavaScript.

We can create a single function definition and then branch base don the different calling signatures of the function.

Here is a complete sample page that implements a JavaScript function that is “pseudo overloaded” with five different calling signatures.



<!DOCTYPE html>
<html>
  <head>
    <script language="JavaScript">
    function DoProcess(opmode, clock, args) {     
       //------------------------------------------------------------------+
       // 1.) We can simulate function overloading by selectivly passing   |
       //     or not passing parameters.                                   |
       //------------------------------------------------------------------+
       //     Since JavaScript is "loosly" typed, function parameters are  |
       //     optional. An parameter that is specified by not recieved     |
       //     will be undefined. (myArgumant == null).                     |
       //------------------------------------------------------------------+
       if(opmode == null) {
         alert("NO OPMODE Recieved");
       }
       
       //------------------------------------------------------------------+
       // 2.)  We can simulate function overloading by selectivly passing  |
       //      DIFFERENT TYPES in the same parameter position.             |
       //------------------------------------------------------------------+
       //      AT this point we know we recieved SOME argument in the      |
       //      first position. We can test the TYPE and execute differnt   |
       //      code depending on what TYPE of parameter we recieved.       |
       //------------------------------------------------------------------+
       else if (typeof opmode == "number" ) {
          alert("Revieved NUMERIC opmode, value : " + opmode);
          }
       else if (typeof opmode == "string" ) {
          alert("Recieved a STRING opmode, value : " + opmode);
       }  
         
       //------------------------------------------------------------------+
       // 3.) We can simulate function overloading by passing a variable   |
       //     NUMBER of arguments.                                         |
       //------------------------------------------------------------------+
       //     In our function definition we can define as many function    |
       //     parameters as we like and then when callign our function we  |
       //     can choose to pass none, some, or all of them. Parameters    |
       //     that are not passed in teh function call will evaluate       |
       //     inside the function as undefined and we can decide what code |
       //     to execute based on that evaluation.                         |
       //------------------------------------------------------------------+
       if (opmode != null) {
          if ( clock == null) {
             alert("OPMODE Recieved BUT NO CLOCK ARGUMENT");
               }
            }
            
       //------------------------------------------------------------------+
       // 4.)  We can simulate function overloading by selectivly passing  |
       //      DIFFERENT SIZE ARRAYS in a parameter position.              |
       //------------------------------------------------------------------+
       //      In the same way we tested for TYPE above we can test that a |
       //      parameter is an array. In addition to logic branching on    |
       //      the type of a parameter, we can pass a variable number of   |
       //      items in an array. Note instanceof has issues working       |
       //      across frames / iframes                                     |
       //------------------------------------------------------------------+
            
         if (args != null) {
            if (args instanceof Array) {               	
               switch(args.length) {
              	  case 3:
                     alert("Recieved an Array: 3rd item = " + args[2]); 
                     break;
              	  case 6:
                     alert("Recieved an Array: 6th item = " + args[5]); 
                     break;                     
                  default: 
                     alert("Recieved an Array but length is invalid"); 
                     break;
                  }
               }
             }            
               
       //------------------------------------------------------------------+
       // 5.)  We can simulate function overloading by selectivly passing  |
       //      a NAME/VALUE PAIR COLLECTION in a parameter position.       |
       //------------------------------------------------------------------+
       //      In the above example we tested to see if the parameter was  |
       //      an instance of teh Array type.                              |
       //      In this case we check to see if we have a parameter that is |
       //      an instance of the JavaScript Object type but NOT an array  |
       //      we know it's a name/vause pair collection. Note that        |
       //      objects CAN be other subtypes (not only arrays) so our code |
       //      needs to know about all the object types that we test for.  |
       //------------------------------------------------------------------+                  
         if (args != null) {
         	 if ((args instanceof Object == true) && 
         	     (args instanceof Array == false)) {
         	    alert("Recieved a collection in the args parameter.");
              alert("Values = [Work : " + args.Work + 
                    "] and [Intensity : " + args.Intensity + "]");
         	    }
          }
          
    }
    </script>
  </head>
  <body>
  	<br /><br />
  	<center>
    <h3>Test Simulated Function Overloading in JavaScript</h3><br />
    <input type="button" value="Pass NO Arguments" 
    onclick="DoProcess()" /><br /><br />
    <input type="button" value="Pass a numeric argument" 
    onclick="DoProcess(999)" /><br /><br />
    <input type="button" value="Pass a String Argument" 
    onclick="DoProcess('Im a STRING', 1)" /><br /><br />
    <input type="button" value="Pass a 3 item Array" 
    onclick='DoProcess(777, 1, [5, 6, 7])' /><br /><br />
    <input type="button" value="Pass a 6 item Array" 
    onclick='DoProcess(777, 1, [33, 66, 77, 88, 99, 100])' /><br /><br />
    <input type="button" value="Pass a collection" 
    onclick='DoProcess(888, 1, {"Work":"3:00", "Intensity":"Maximum"})' />
    <br /><br />   
  </center>
  </body>
</html> 


Best Tools for Professional JavaScript Development

I’ve been doing a lot og Client Side Development lately and am plannign on doing a lot more. HTML5, JavaScript, CSS – Oh My.

I’m building a work-out timer and there is a LOT of JavaScript so as I started looking for a Testing Framework I found myself building a list of options for the various types of JavaScript tools (I’ll address CSS and HTML tools later.)

The “code protection” section happened less because I want to hide code and more that I want to minimize my growning JavaScript dependencies.

I’ll post about my choices in the near future but wanted to share the list first.

A few notes about the list below.

I’ve added the ones that I feel merit consideration for MY work. Feel free to suggest additions, but I have intentionally omitted many choices for a variety of reasons. Currency, Adoption, support, etc.

Some are commercial products and others are free.

In the Editors (and IDE) section, I know there are hundreds. In my list are some Windows Only choices and some Linux / Mac choices as cross platform is very important to me.

Here is the raw list, I’ll comment on each category as I make selections.

Testing

Pavlov – https://github.com/mmonteleone/pavlov
JSSPEC – http://code.google.com/p/jsspec/
SvrewUnit – https://github.com/nkallen/screw-unit
Jasmine – http://pivotal.github.com/jasmine/

Mocking Frameworks

JSmock – http://jsmock.sourceforge.net/
JSmickito – http://jsmockito.org/
MockMe – http://johanneslink.net/projects/mockme.html
Qmock – https://github.com/andybeeching/qmock
JSHamcrest – http://jshamcrest.destaquenet.com/

Editors

JetBrains WebStorm – http://www.jetbrains.com/webstorm/
VWD Express – http://www.microsoft.com/express
CoffeeCup – http://www.coffeecup.com/html-editor/
NetBeans – http://netbeans.org/
Aptana – http://www.aptana.com/
Komodo Edit – http://www.activestate.com/komodo-edit
Edit Rocket – http://www.editrocket.com/features/javascript_editor.html
Komposer – http://www.kompozer.net/
Antechnius JavaScript Editor – http://www.c-point.com/
1st JavaScript Editor Pro – http://yaldex.com

Code Protection

JSCruncher Pro – http://domapi.com/jscruncherpro/
YUI Compressor – http://developer.yahoo.com/yui/compressor/
Javascript Obfuscator – http://java-applets.org/javascript-obfuscator-linux.html
JavaScript Obfuscator – http://javascript-source.com/buy.html
AntiSoft  HTML Protector http://www.antssoft.com/order.htm
Closure Compiler – http://code.google.com/closure/
JSMin – http://www.crockford.com/javascript/jsmin.html
Digua – http://digua.sourceforge.net/
ObfuscateJS – http://tools.2vi.nl/ + http://linux.softpedia.com/get/Utilities/ObfuscateJS-10350.shtml
Stunnix – http://www.stunnix.com/prod/jo/
Thicket – http://www.semdesigns.com/Products/Obfuscators/ECMAScriptObfuscator.html
Jasob – http://www.jasob.com/
JCE Pro – http://syntropy.se/en/2010/04/jce_pro_downloads/
Scripts Encrypter – http://www.dennisbabkin.com/screnc/
Shanes Obfuscator – http://www.shaneng.net/Main/JavaScriptObfuscator
Jammer – http://rzr.online.fr/docs/shop/jammer.htm
JS Strong – http://www.stronghtml.com/tools/js/
JavaScript Scrambler – http://www.quadhead.de/jss.html
HTML Protect – http://java-applets.org/javascript-obfuscator-linux.html
IonCube HTML Obfuscator – http://www.ioncube.com/html_encoder.php

Play Sound in HTML5 and cross browser support with backward compatability.

In the last post in this series [ read here ] I added the clock timing logic to the HTML workout timer.

The next feature to add is round and interval audio. I want to ring a bell at the beginning and the end of each round, a warning before a change in work state, etc.

This is quite a bit more difficult than it sounds because we need to support both the differences between HTML5 implementation specifics in each of the modern browsers as well as  support still popular older browsers that only support pre “5″ versions of HTML.

I wanted code that would play an Audio file in the current versions of Internet Explorer, Firefox, Chrome, Opera and Safari on Windows, Firefox, Chrome, and Safari on the Mac and on old HTML 4 browsers. As it turns out some current browsers will play .wav but not .mp3 files. Some with play .mp3 but not .wav and some will play both.

So, I built a small test application that would play in all !

The UI was simple enough:

Lets look at the code and I’ll call out the notable points of interest.


&lt;!DOCTYPE html&gt;
&lt;html&gt;  
&lt;head&gt;
&lt;title&gt;Play Audio&lt;/title&gt;
&lt;script src=&quot;script/jquery-1.6.2.min.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script src=&quot;script/modernizr-latest.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
&lt;script type=&quot;text/javascript&quot;&gt;
    var currentFile = &quot;&quot;;
    function playAudio() {

        var oAudio = document.getElementById('myaudio');
        // See if we already loaded this audio file.
        if ($(&quot;#audiofile&quot;).val() !== currentFile) {
            oAudio.src = $(&quot;#audiofile&quot;).val();
            currentFile = $(&quot;#audiofile&quot;).val();
        }
            var test = $(&quot;#myaudio&quot;);
            test.src = $(&quot;#audiofile&quot;).val();
        oAudio.play();   
    }
    
    $(function() {
        if (Modernizr.audio) {
            if (Modernizr.audio.wav) {
                $(&quot;#audiofile&quot;).val(&quot;sounds/sample.wav&quot;); 
            }
            if (Modernizr.audio.mp3) {
                $(&quot;#audiofile&quot;).val(&quot;sounds/sample.mp3&quot;);
            }
        }
        else {
          $(&quot;#HTML5Audio&quot;).hide();
          $(&quot;#OldSound&quot;).html('&lt;embed src=&quot;sounds/sample.wav&quot; 
                                      autostart=false width=1 height=1 
                                      id=&quot;LegacySound&quot; 
                                      enablejavascript=&quot;true&quot; &gt;');
        }

    });
&lt;/script&gt;
&lt;/head&gt;
  
&lt;body&gt;
  &lt;div style=&quot;text-align: center;&quot;&gt; 
    &lt;h1&gt;Click to Play Sound&lt;br /&gt;&lt;/h1&gt;
    &lt;div id=&quot;HTML5Audio&quot;&gt;
    &lt;input id=&quot;audiofile&quot; type=&quot;text&quot; value=&quot;&quot; style=&quot;display: none;&quot;/&gt;
    &lt;br /&gt;
  
    &lt;button id=&quot;play&quot; onclick=&quot;playAudio();&quot;&gt;
        Play
    &lt;/button&gt;
    &lt;/div&gt;
    &lt;audio id=&quot;myaudio&quot;&gt;
        &lt;script&gt;
        function LegacyPlaySound(soundobj) {
          var thissound=document.getElementById(soundobj);
          thissound.Play();
        }
        &lt;/script&gt;
        &lt;span id=&quot;OldSound&quot;&gt;&lt;/span&gt;        
        &lt;input type=&quot;button&quot; value=&quot;Play Sound&quot;  
               onClick=&quot;LegacyPlaySound('LegacySound')&quot;&gt;
    &lt;/audio&gt;

&lt;/div&gt;

&lt;/body&gt;
&lt;/html&gt;

First, you will notice that I’ve included jQuery as I now do in all my web based UI and I’ve included Modernizr, which I’ll use to determine where the HTML5 audio tag is supported and if it is, what audio file format that I need to use for the browser that I happen to be running in.

I’ve created a “sounds” directory and sound files named “sample.wmv” and “sample.mp3″.

Note the declaration of an audio element on line 54. If the browser supports the HTML5 Audio element the code between lines 54 and 64 will be ignored. If the browser does not support HTML5 audio then that markup will be rendered (including the JavaScript). The actual LegacySound object that gets played on line 63 is only needed if the browser is not HTML5 and it will be created by some JavaScript when the page is loaded only if it is needed,

Lines 6 to 20 are a JavaScript function to play the HTML5 audio element. Note that I’ve used a technique to improve performance slightly if name of the audio file to be played has not changed since the last time the function was called.

Beginning on line 22 code will be executed when the document is ready (loaded).

Line 23 tests to see if the HTML Audio tag is supported.

Then we check to see which media file type is supported.

If the HTML5 Audio tag is not supported then line 32 hides the user interface elements that would be used with the HTML Audio and line 33 creates the embedded media object to be played by older browsers.

I’ve tested this code in all the browsers listed above as well as Netscape 7 for HTML 4 compatibility.

You can click [ HERE ] to download a working sample.

ASP.NET Password Strength Indicator with jQuery Plugin.

Password strength is a key factor in account security for weeb applications. As developers we all have a basic understanding of what a secure password is but the averge consumer of internet applications doesn’t so adding a visual indicator when your user selectes a password is a great feature.

There are many, many plugins that we could select from to implement this feature I’ve selected this one which makes things very easy.

http://plugins.jquery.com/project/password_strength


&lt;%@ Page Title=&quot;Home Page&quot; Language=&quot;C#&quot; MasterPageFile=&quot;~/Site.master&quot; 
    AutoEventWireup=&quot;true&quot; CodeFile=&quot;Default.aspx.cs&quot; Inherits=&quot;_Default&quot; %&gt;

&lt;asp:Content ID=&quot;HeaderContent&quot; runat=&quot;server&quot; ContentPlaceHolderID=&quot;HeadContent&quot;&gt;
    &lt;script src=&quot;Scripts/jquery-1.4.1.js&quot; type=&quot;text/javascript&quot;&gt;&lt;/script&gt;
    &lt;script src=&quot;Scripts/jquery.password_strength.js&quot; type=&quot;text/javascript&quot;&gt;
    &lt;/script&gt;
    &lt;style type=&quot;text/css&quot;&gt; 
    .password_strength {
	    }
    .password_strength_1 {
	    background-color: #fcb6b1;
	    }
    .password_strength_2 {
	    background-color: #fccab1;
	    }
    .password_strength_3 {
	    background-color: #fcfbb1;
	    }
    .password_strength_4 {
	    background-color: #dafcb1;
	    }
    .password_strength_5 {
	    background-color: #bcfcb1;
	    }
    &lt;/style&gt; 
&lt;/asp:Content&gt;
&lt;asp:Content ID=&quot;BodyContent&quot; runat=&quot;server&quot; ContentPlaceHolderID=&quot;MainContent&quot;&gt;
    &lt;h2&gt;Password Strength&lt;/h2&gt;

    &lt;table style=&quot;border-spacing: 0px; border-style: none&quot;&gt;
      &lt;tbody&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;&lt;label&gt;User Name:&lt;/label&gt;&lt;/td&gt;
        &lt;td&gt;
           &lt;asp:TextBox ID=&quot;username&quot; runat=&quot;server&quot; Width=&quot;200px&quot;&gt;&lt;/asp:TextBox&gt;
        &lt;/td&gt;
      &lt;/tr&gt;
      &lt;tr&gt;
        &lt;td style=&quot;text-align: right&quot;&gt;&lt;label&gt;Password:&lt;/label&gt;&lt;/td&gt;
        &lt;td&gt;
            &lt;asp:TextBox ID=&quot;password&quot; class=password runat=&quot;server&quot; 
                ClientIDMode=&quot;Static&quot; TextMode=&quot;Password&quot; Width=&quot;200px&quot;&gt;
            &lt;/asp:TextBox&gt; 
        &lt;/td&gt;
      &lt;/tr&gt;
      &lt;/tbody&gt;
    &lt;/table&gt;

  
&lt;script type=&quot;text/javascript&quot;&gt;
    $('form').attr('autocomplete', 'off');
    $('#password').password_strength();
&lt;/script&gt; 

&lt;/asp:Content&gt;

In the code above I’ve used in-line CSS and script for the sake of learning simplicity.

The CSS is used by the plugin to set the color that corresponds with the “level” of the password as entered.

The script block starting on line 50 turns autocomplete off for the form (we’re working with a password after all) and applies the password strength functionality to the ASP.NET textbox controll names “password:.

As with all the ASP.NET jQuery work that we’ve been doing, we must set the Client Id Mode to “static” so tha tthe ASP.NET runtime does not modify the client ID of the emitted HTML text box.


You can download a working sample [ HERE]


Filtering an ASP.NET GridView control with jQuery

 As I’ve been swimming in the great jQuery lake I discovered the jQuery QuickSearch Plugin,

As WebForms developers we often display lots of data using a gridview control.

I though it would be neet to set up using the jQuery QuickSearch plugin with the Gridview.

Here’s how it works.

Ihave a GridView wired to some sample data. For demo simplicity I’m using an XMLDataSource and reading from an XML file in my App_Data directory.

When the user starts to type into the Filter Text Box the rows in the table are filtered, meaning rows that don’t match the character(s) entered are hidden from view.

As the user continues to type, the list is filtered further.

The ASPX Page Markup is as follows.
Read the rest of this entry »

Implementing Mutually Exclusive CheckBoxes with jQuery

The ASP.NET Ajax Control Toolkit contains a control extender for making a set of ASP.NET CheckBoxes mutually exclusive [ See HERE ]. In this post I’ll demonstrate implementing Mutually Exclusive CheckBoxes with jQuery.

ASP.NET Checkboxes are, of course, server-side controls. If you’ve been following along with this series, or you using ASP.NET WebMatrix or MVC instead of WebForms, you may want to be leveraging HTML elements instead of server-side controls so my sample code will demonstrate doing this with both HTML input elements (checkboxes) as well as ASP.NET CheckBox controls.

This requires two slightly different methods because of the way ASP.NET emits markup for the ASP.NET CheckBox controls.

Here is a screen shot :

Read the rest of this entry »

Replacing the ACT PagingBulletedList with the jQuery ListNav Plugin.

The Ajax Control Toolkit includes a control extender [ The Paging Bulleted List Control Extender ] that lets you create a list that the user can filter by clicking on an index indicator.

This can be very useful, especially when your list is very large.

The jQuery ListNav Plug-In lets you do this with any unordered list.

What’s more, since the list is a standard HTML element, we could dynamicaly add items to the list in our client side JavaScript code.

When you run my sample application the whole list looks like this :

Then when I click on the “B” in the navigation bar the list is reduced to only those items that begin with the letter “B”.

The code is long but simple:

Read the rest of this entry »

I recently received this email from an MSJoe blog reader.

Hi Joe, thanks for the posts about jquery..

 

I’m now wondering, we are using the ms ajax toolkit. I like the simple use of it. Now doing jquery you will have to write javascript, which will have the advantage that all cpu cycles are spend on the client side for rendering the validation controls (the toolkit does something on serverside first)

 

Do you see any advantage of doing the jquery way instead of the ajax toolkit? Or is it just releasing yourself from a dependency on the toolkit and the minimal extra rendering effort for the server with the toolkit?

 

Thanks,

With the senders permission, I thought it would be interesting to answer here, it’s a great question and one that I’ve received many times. .

To be clear, Microsoft continues to support the Ajax Control Toolkit. Support though, means bug fixes.

If the Ajax Control Toolkit works for you, you certainly can continue to use it. I certainly wouldn’t spend a bunch of time retrofitting pages that use the Ajax Control Toolkit if just to switch to jQuery.

But, in my opinion,  for new development there are a number of advantages to using jQuery.

Not the least of which is that the Ajax Control Toolkit is “frozen”. Not only will there be no new controls / extenders, but there are no feature enhancements planned for any of the controls. Most of the controls are “version one" at best. There will not be a version 2 (or even a version 1.1).

Even thought the ACT (Ajax Control Toolkit) is “Open Source”, folks have adopted it as a “Microsoft Product” and it hasn’t really enjoyed much up-take by community contributors.

Since it’s open source, you could modify or extend it yourself, but it’s a pretty big time investment to come up to speed.

jQuery, jQuery UI, and the plethora of jQuery Plug-Ins offer a great alternative, but not a seamless one.

While jQuery is new, frequently updated, rich and elegant, and has a vibrant active community who contributes new plugins every day, for the Classic ASP.NET Developer, there is a big perspective change to tackle.

jQuery is JavaScript. There is no server-side technology involved.

Many  “WebForms”  developers are new to JavaScript, CSS, and the DOM.

When you use jQuery for your ASP.NET User Interface, there are no “server-side” events for you to code against and no “server-side” properties either (like the user entered value of a text box).

In a WebForms application, basically all control events cause a form post-back.

Using jQuery (CSS and HTML) the UI elements run entirely on the CLIENT. When you need to execute code on the server (C#, VB.NET etc.) you have two options.

  1. Submit the complete form back o the server.
  2. Connect a JavaScript function to an event handler for the user interface element and make a JavaScript Ajax call back to a service method on the server.

That’s a pretty different model that the one WebForms developers are used to.

Apart from the above, what are the advantages of moving to this web application development model?

Well, I think there are several.

  1. The browser doesn’t have to be dumb. Browsers can run CODE, but when we don’t implement anything in JavaScript we haven’t federated any logic. Even though we have a powerful processor on the user’s computer where the browser is running, we’re not using any of that computer’s processing power. That means we’re consuming more resources on the server than we need to. This has a negative impact on your performance and scalability.
  2. A UI that responds to user input and executes logic, updates the user interface and interacts with the server without the user needing to wait for a page post back makes for a better User Experience.
  3. This type of experience is increasingly expected by web application users.
  4. JavaScript has become ubiquitous. Your JavaScript skills can be useful on the client, server and desktop.
  5. Everything is Open Source JavaScript so you can modify to your heart’s content.

Does that make sense ?

ASP.NET Dropdown Search with jQuery

The Ajax Control Toolkit includes a ListSearch [ see HERE ] control extender that can me used to extend a list or drop down list with a filtering feature by which the control will start to narrow the available options in the list to the ones that include the characters that the user has entered.

So when we use a drop down list for the selection of an item, and we enter (set focus) on the control, then the control expands. 

Then when we start to type, we want the list to hide items that do not contain the character sequence that we have typed.

I’ve implemented this feature using Unobtrusive Fast-filter Dropdown

Implementing this plugin (abbreviated UFD) with an ASP.NET DropDownList is easy.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
    AutoEventWireup='true' CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
                                ContentPlaceHolderID='HeadContent'>
    <link href='Content/themes/redmond/jquery-ui.css' rel='stylesheet'
                                                      type='text/css' />
    <link href='Styles/udf/ufd-base.css' rel='stylesheet' type='text/css' />
    <link href='Styles/udf/plain/plain.css' rel='stylesheet' 
                                            type='text/css' />
    <script src='Scripts/jquery-1.4.4.js' type='text/javascript'></script>
    <script src='Scripts/jquery-ui-1.8.13.js' type='text/javascript'></script>
    <script src='Scripts/jquery.ui.ufd.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit 
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <p>
        You can also find 
        <a href='http://go.microsoft.com/fwlink/?LinkID=152368&clcid=0x409'
            title='MSDN ASP.NET Docs'>documentation on ASP.NET at MSDN</a>.
    </p>
    <hr />

    <label for='SelectCountry'>Choose a country:</label><br /><br />
    
    <asp:DropDownList id='SelectCountry' name='SelectCountry' runat='server' 
                      ClientIDMode='Static'>
        <asp:ListItem Text='Afghanistan' Value='Afghanistan'></asp:ListItem>
        <asp:ListItem Text='Albania' Value='Albania'></asp:ListItem>
        <asp:ListItem Text='Algeria' Value='Algeria'></asp:ListItem>
        <asp:ListItem Text='Bahrain' Value='Bahrain'></asp:ListItem>
        <asp:ListItem Text='Bangladesh' Value='Bangladesh'></asp:ListItem>
        <asp:ListItem Text='Barbados' Value='Barbados'></asp:ListItem>
        <asp:ListItem Text='Cambodia' Value='Cambodia'></asp:ListItem>
        <asp:ListItem Text='Cameroon' Value='Cameroon'></asp:ListItem>
        <asp:ListItem Text='Canada' Value='Canada'></asp:ListItem>
    </asp:DropDownList>

    <br/>

    <script type='text/javascript' >
        $(function () {
            $('#SelectCountry').ufd({ log: true });
        });    
    </script>

</asp:Content>


You can garb the working example [ HERE ]


ASP.NET User Input via the jQuery UI Slider

The Ajax Control Toolkit includes a “Slider” and a “MultiHandleSlider” control extender that lets your user fill a textbox with a numeric value by dragging one or more markers along a line or “axis”.

One “slider” means manipulating one value, multiple sliders means manipulating multiple values.

This is another way to add a visual component to data entry, which may be faster, or lead to greater accuracy and convenience when data is being entered.

I’m replacing the Ajax Control Toolkit slider with the jQuery UI Slider.

Here is a screen shot of the working sample.

And here is our page markup :


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
    AutoEventWireup='true' CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
                                ContentPlaceHolderID='HeadContent'>
<link href='Content/themes/base/jquery.ui.all.css' rel='stylesheet' 
                                                   type='text/css' />
<script src='Scripts/jquery-1.4.4.js' type='text/javascript'></script>
<script src='Scripts/jquery-ui-1.8.13.js' type='text/javascript'></script>
<style>
    .valueout 
    {
        border: 0; 
        color:#f6931f; 
        font-weight:bold;
    }
</style>
<script type='text/javascript'>
    $(function () {
        // Add one slider to the first target DIV.
	    $('#slider').slider({
	        value: 100,
	        min: 0,
	        max: 500,
	        step: 50,
	        slide: function (event, ui) {
	            $('#amount').val('$' + ui.value);
	        }
	    });
	    $('#amount').val('$' + $('#slider').slider('value'));

	    // Add two sliders to the second target DIV.
	    $('#slider-range').slider({
	        range: true,
	        min: 0,
	        max: 500,
	        values: [75, 300],
	        slide: function (event, ui) {
	            $('#amountrange').val('$' + ui.values[0] 
				                          + ' - $' + ui.values[1]);
	        }
	    });
	    $('#amountrange').val('$' + $('#slider-range').slider('values', 0) +
		                   ' - $' + $('#slider-range').slider('values', 1));

	});
</script>

</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit 
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <hr />
   
	<label for='amount'>Donation amount ($50 increments):</label><br /><br />    
    <asp:TextBox ID='amount' CssClass='valueout' runat='server'    
                 ClientIDMode='Static'>
    </asp:TextBox>
    <br /><br />        
    <div id='slider' style='width: 300px;'></div><br />

    
    <hr />
    <asp:Button ID='Button1' runat='server' Text='Submit' 
	                                        onclick='Button1_Click' />
    <br /><br />
    <asp:Label ID='LabelTestResult' runat='server' Text=''></asp:Label>
    <hr />
    
	<label for='amountrange'>Range:</label>	
    <asp:TextBox ID='amountrange' CssClass='valueout' runat='server' 
                                  ClientIDMode='Static'>
    </asp:TextBox><br /><br />    
    <div id='slider-range'  style='width: 300px;'></div>

</asp:Content>

The actual value is a string stored in the textboxes created on lines #58 and #71.

Note the setting of the initial value, min, max, step, and range parameters.

Note also lines #28 and #40 where slider value is used to set our textboxes.

Since those text boxes are ASP.NET Server Side controls we can easily access them in our code-behind.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        LabelTestResult.Text = 'Thanks - ' + amount.Text 
		                                   + ' is a lot of money!';
    }
}


You can download a working sample [ HERE ]


Numeric Up Down Input using the jQuery UI Spinner

The AJAX Control Toolkit includes a Numeric Up/Down Control Extender that lets you turn a text box into a numeric Up / Down input control.

There is a slick jQuery UI plugin – the jQuery UI Spinner - that lets us do this without the Ajax Control Toolkit and have pretty detailed control over the way our input works.

Some of the built-in capabilities include:

  • Mouse Wheel Support
  • Control over the Mouse Wheel Increment sensitivity
  • Variable “step” increments
  • Set-able Minimum and Maximum Values

Here is our demo UI.

And here is our code :


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='Content/themes/base/jquery.ui.all.css' rel='stylesheet' 
      type='text/css' />
<link href='Styles/Site.css' rel='stylesheet' type='text/css' />
<link href='Styles/ui.spinner.css' rel='stylesheet' type='text/css' />
<script src='Scripts/jquery-1.4.4.js' type='text/javascript'></script>
<script src='Scripts/jquery-ui-1.8.13.js' type='text/javascript'></script>
<script src='Scripts/ui.spinner.js' type='text/javascript'></script>
<script type='text/javascript'>
jQuery().ready(function ($) {
	$('#updown').spinner({ min: -100, max: 100 });
	$('#updownfast').spinner({ min: -1000, max: 1000, increment: 'fast' });
	$('#updownhide').spinner({ min: 0, max: 100, showOn: 'both' });
	$('#updownnull').spinner({ min: -100, max: 100, allowNull: true });
	$('#updowndisable').spinner({ min: -100, max: 100 });
	$('#updownmaxlen').spinner();

	$('#updownconfig').spinner(
	   { min: -1000, max: 1000, step: 1, increment: 'fast' }
	   );
	$('#updownmax').spinner().change(function ()
	   { $('#updownconfig').spinner('option', 'max', 
	                                 parseInt($(this).val())); } 
	   );
	$('#updownmin').spinner().change(function ()
	   { $('#updownconfig').spinner('option', 'min', 
	                                 parseInt($(this).val())); }
	   );
	$('#updownstep').spinner().change(function ()
	   { $('#updownconfig').spinner('option', 'step', 
	                                 parseInt($(this).val())); }
	   );  
	$('#updownspeed').change(function ()
	   { $('#updownconfig').spinner('option', 'increment', $(this).val()); }
	   );
	$('#updownmousewheel').change(function ()
	   { $('#updownconfig').spinner('option','mouseWheel',
	                                 $(this).is(':checked')); }
	   );
	$('#enable').click(function () 
	 { $('#updowndisable').spinner('enable'); });
	$('#disable').click(function () 
	 { $('#updowndisable').spinner('disable'); });
	$('#GetValue').click(function () 
	 { alert($('#updown').spinner('value')); });
	$('#destroy').click(function () 
	 { $('#updown').spinner('destroy'); });

});
</script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
     ContentPlaceHolderID='MainContent'>
<h2>
    Welcome to ASP.NET!
</h2>
<br />
Up Down : 
<asp:TextBox ID='updown' runat='server' ClientIDMode='Static' Text='0'>
</asp:TextBox>
<input type='button' id='GetValue' value='Get Value' /> 
<input type='button' id='destroy' value='Destroy' />
<br /><br />

Fast Up / Down :	
<asp:TextBox ID='updownfast' runat='server' ClientIDMode='Static' Text='0'>
</asp:TextBox> 
<br /><br />
    
Up / Dopwn Hidden: 
<asp:TextBox ID='updownhide' runat='server' ClientIDMode='Static' Text='0'>
</asp:TextBox> Except for  When Active !
<br /><br />   
	    
<hr />
<div id='example'>
<table class='grid'>
  <tr>
     <td>Configurable Up/Down:</td>
     <td>
     <asp:TextBox ID='updownconfig' runat='server' 
	              ClientIDMode='Static' Text='0'>
     </asp:TextBox> 
     </td>
   </tr>
   <tr>
      <td>Maximum:</td>
      <td>
      <asp:TextBox ID='updownmax' runat='server' 
	               ClientIDMode='Static' Text='1000'>
      </asp:TextBox> 
      </td>
   </tr>
   <tr>
      <td>Minimum:</td>
      <td>
      <asp:TextBox ID='updownmin' runat='server' 
	               ClientIDMode='Static' Text='-1000'>
      </asp:TextBox> 
      </td>
   </tr>
   <tr>
      <td>Step:</td>
      <td>
      <asp:TextBox ID='updownstep' runat='server' 
	               ClientIDMode='Static' Text='1'>
      </asp:TextBox> 
      </td>
   </tr>
   <tr>
      <td>Speed:</td>
      <td>
         <select id='updownspeed'>
            <option value='slow'>Slow</option>
            <option selected='selected' value='fast'>Fast</option>
         </select>
      </td>
   </tr>
   <tr>
      <td>Mouse Wheel:</td>
      <td>
         <input type='checkbox' id='updownmousewheel' checked='checked' />
      </td>
   </tr>
</table>
</div>
<hr />
<br />
    <asp:Button ID='ButtonSubmit' runat='server' Text='Submit' 
        onclick='ButtonSubmit_Click' /><br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>
</asp:Content>


The ui.spinner.css file takes care of positioning the Up / Down buttons next to the text bix that they will apply to.

Note that in the body of the markup the text boxes can be either html input elements with type set equal to text or ASP.NET TextBox controls with the ClientIdMode set to static.

Whichever way you choose you can specify a starting numberic value as a string.

The “magic” happens in the jQuery code that you see above between lines 11 and 44.

I think the code’s functionality is pretty straight forward and looking at the code reveals many of the optional parameters.

Simplifying user input helps reduce data input errors!

You can download a working sample [ HERE ].


Embedding a jQuery HTML Input Editor in an ASP.NET page.

Sometimes we need users to be able to enter fomated input / text.

There are many embedable WYSIWYG HTML inpt boxes available. [ See HERE ]

I chose HTMLBox 4.01 becuase it is easy to style [ DEMO HERE ] but there are many good ones and you should pick the one that best meets your needs.

My implementation looks like this.

When I’ve entered some formatted text I can switch to HTML view and see the markup.

One of the things tat I especially like about HTMLBox is that it exposes events for the appropriate icons like “File Open”

My page markup looks like this:


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
         Inherits='_Default'  %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/com.remiya.jquery.codify.min.js' 
	        type='text/javascript'>
    </script>
    <script src='Scripts/htmlbox.colors.js' type='text/javascript'></script>
    <script src='Scripts/htmlbox.styles.js' type='text/javascript'></script>
    <script src='Scripts/htmlbox.syntax.js' type='text/javascript'></script>
    <script src='Scripts/htmlbox.undoredomanager.js' type='text/javascript'>
    </script>
    <script src='Scripts/htmlbox.full.js' type='text/javascript'></script>
    <script type='text/javascript'>
        $(function () {
           
        });
    </script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit 
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
<h2>HTML Input</h2>

<asp:TextBox ID='htmlbox' runat='server' TextMode='MultiLine' Rows='20' 
             Columns='80' ClientIDMode='Static'></asp:TextBox><br />    
<asp:Button ID='SubmitButton' runat='server' Text='Submit' 
            onclick='SubmitButton_Click' /><br /><br />

<asp:Label ID='LabelResult' runat='server'></asp:Label>

<script  type='text/javascript'>
var hb_icon_set_blue;
hb_icon_set_blue = $('#htmlbox').css('height', '100')
                                .css('width', '600').htmlbox({
   toolbars: [
	         ['cut', 'copy', 'paste', 'separator_dots', 'bold', 'italic',
              'underline', 'strike', 'sub', 'sup', 'separator_dots', 'undo',
              'redo', 'separator_dots', 'left', 'center', 'right', 'justify',
              'separator_dots', 'ol', 'ul', 'indent', 'outdent', 
              'separator_dots', 'link', 'unlink', 'image'],
		      ['code', 'removeformat', 'striptags', 'separator_dots', 
			   'quote','paragraph', 'hr', 'separator_dots',
              { icon: 'new.gif', tooltip: 'New', command: function () 
                                { hb_icon_set_blue.set_text('<p></p>'); } },
			 { icon: 'open.gif', tooltip: 'Open', command: function () 
                                { alert('Open') } },
			 { icon: 'save.gif', tooltip: 'Save', command: function () 
                                { alert('Save') } }
		  ]
	],
        icons: 'default',
        skin: 'blue'
    });
</script>

</asp:Content>

But, just adding the jQUery and HTML Box libraries to our page and wiring the jQuery plugin to an ASP.NET Multi Line Textbox will not get us to where we really need to be.

If we do just that muich and run our page we will see this error.



The above is generated by a built in security feature of .NET that prevents the user from submitting markup or anything that might be a security concern.

We’ll need to tell ASP.NET to allow markup to be posted back

WARNING: Doing this means we are explicitly telling ASP.NET that we will be responsable for making sure that whatthe user posts back to the server is SAFE ! – All user input should be considered evil untill we prove otherwise.

In order to permit the markup to be posted back we need to do two things,

1.) We need to add a directive to the system.web section of the web.config file and set the Validation Mode to 2.0


  <system.web>
      <httpRuntime requestValidationMode='2.0' />
  </system.web>

2.) Then, in the page itself we need to add a page directive to tell ASP.NET not to validate the page


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
         Inherits='_Default' ValidateRequest='false' %>

Now the page will submit.

Since we turned validation off, we should insure security before we use whatever the user entered in the WYSIWYG box. (Like storing it in a database or displaying it on a page.

In our button click event handler we simply encode the text box value before we use it.


    protected void SubmitButton_Click(object sender, EventArgs e)
    {
        LabelResult.Text = Server.HtmlEncode(htmlbox.Text);
    }

You can download a working ASP.NET 4 sample [ HERE ]


The Ajax Control Toolkit contains a number of control extenders to restrict input from the user. Two are the Filtered Textbox Extender and the MaskEdit Extender.

WARNING – In a web application, restricting user input in the browser DOES NOT SECURE YOUR WEB APPLICATION. To insure that you application is secure you MUST insure the safety of user input in the server-side code !

The jQuery ecosystem has many plugins available to control user input and in the code below I’ve selected two to simulate the Ajax Control Toolkit extenders listed above.

Here’s what our UI will look like.

Lets look at the code :


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/jquery.filter_input.js' type='text/javascript'>
	</script>
    <script src='Scripts/jquery.maskedinput-1.3.js' type='text/javascript'>
	</script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit 
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>

       <input id='text_input_1'  type='text' /> <- Numbers Only.<br /><br /> 
       <input id='text_input_2'  type='text' /> <- Lower Case Letters.
	   <br /><br /> 
       <input id='text_input_3'  type='text' /> <- URL safe characters.
	   <br /><br /> 
       <hr />
       <input id='date'  type='text' /> <- Date.<br /><br /> 
       <input id='phone'  type='text' /> <- Phone.<br /><br /> 
       <input id='ssn'  type='text' /> <- Social Security Number.<br /><br /> 
       <input id='otherphone'  type='text' /> <- Phone.<br /><br /> 

        <script type='text/javascript'>
		$(function () {
			// only numbers are allowed
			$('#text_input_1').filter_input({ regex: '[0-9]' });

			// only lowercase alphabets are allowed
			$('#text_input_2').filter_input({ regex: '[a-z]' }); 

			// only URL safe characters are allowed
			$('#text_input_3').filter_input({ regex: '[a-zA-Z0-9_]' });

			$('#date').mask('99/99/9999');
			$('#phone').mask('(999) 999-9999');
			$('#ssn').mask('999-99-9999');
			$('#otherphone').mask('(999) 999-9999', { placeholder: 'x' });
		});
    </script>  
</asp:Content>

The first three textboxes are “filtered” do that when the user presses a character key that is not one of the set specified in the filter’s regular expression, that key will be ignored.

Since the jQuery Filter Extender is Regular Expression based, you can get much more advanced in controling usert input by writing your own regular expressions.

The second set are “masked”. The textbox will guide the user through a template like the “phone number” input below.

Why use a free form text box when the input needs to be specifically tailored to a particular format?

Replacing the Ajax Control Toolkit DragPanel Control Extender with jQuery

The Ajax Control Toolkit includes a DropPanel Control Extender that lets you drag and drop content thereby moving it around on your web page [ more HERE ]. 

jQuery, or more specifically jQueryUI has Drag-and-Drop built-in.

Yup – like a lot of stuff in this series that means it’s just REALLY easy to get the effect you want using jQuery

Since this series is about showing how to do with jQuery the sort of things you would have previously done with the Ajax Control Toolkit, I’m going to defer catching the “drop” events to a future entry.

Here is the effect we’re looking for.

 

Drag and Drop …..

After including jQuery and jQUeryUI  (script & CSS) here is the code for the page.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
                        Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
                                ContentPlaceHolderID='HeadContent'>
    <link href='Styles/jquery-ui-1.8.13.custom.css' rel='stylesheet' 
                                                type='text/css' />
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
                              ContentPlaceHolderID='MainContent'>
    <h2>Draggable Panel !</h2>
    <br />
    <div class=demo>
        <div id=draggable class=ui-widget-content>
            <p>
            <br />
            I'm an AJAX Draggable Container.
            <br /><br />
            You could catch drop events and build a configurable UI.

            </p>
        </div>
    </div>

    <div>    
        <p>
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. 
        Mauris varius ullamcorper lacus, ac pharetra libero commodo eu. 
        Aenean auctor imperdiet libero, sit amet scelerisque lorem placerat
        quis. Phasellus pretium, lacus eget euismod cursus, nunc nibh semper
        urna, at blandit elit nisl non dui. Sed blandit dignissim tellus, 
        in egestas orci facilisis vel. Curabitur consequat ante vel mauris
        accumsan rutrum. Aliquam lorem est, ornare eget mollis sit amet, 
        vestibulum et diam. Phasellus cursus massa sodales metus 
        luctus sed blandit quam rhoncus. Proin nunc risus, scelerisque eu 
        sagittis in, gravida vitae lectus. Maecenas et ipsum ac mauris 
        condimentum accumsan ac et ligula. Phasellus mattis, tortor quis 
        rutrum mollis, ante eros dictum leo, ac venenatis augue nisl sit 
        amet mauris. Maecenas cursus, arcu nec egestas molestie, leo 
        lectus pellentesque sapien, eu sollicitudin urna dolor vitae 
        nisl. Proin lobortis, tortor quis congue lacinia, arcu elit 
        consequat erat, vestibulum aliquet lorem massa sed leo. Suspendisse 
        volutpat odio in mauris cursus aliquam. Nullam sed sapien sit amet mi 
        laoreet sagittis. Integer rutrum lacus quis felis venenatis porta. 
        </p>
    </div>         

    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/jquery-ui-1.8.1.custom.min.js' 
	                                     type='text/javascript'>
    </script>

    <style>
    #draggable { width: 150px; height: 150px; padding: 0.5em; }
</style>

    <script type='text/javascript'>
        $(function () {
            $('#draggable').draggable();
        });
    </script>                 
</asp:Content>


All we’re doing here is specifying a class to apply to the area that we want to be draggable then using a jQuery selector to access any page element that uses that class and calling the jQueryUI dragable() method.

Have fun !


Implementing Collapse Panels with jQuery.

The Ajax Control Toolkit has a Collapse Panel Control Extender [ see HERE ] that allows you to hide or show sections of content in your web page. This ability can be very useful as we evolve our UIs more toward “Single Page” interfaces.

There are many ways to accomplish this using jQuery and I’ve chosen a slick little plugin by Darren Ingram [ get it HERE ]

The UI behavior is simple. We have a set of content in a container (a div in this case)

When the user clicks on the title bar the container collapses leaving only the title bar.

The code is simple becuase the PlugIn does all the work for us.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
    AutoEventWireup='true' CodeFile='Default.aspx.cs' Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
                                ContentPlaceHolderID='HeadContent'>
<link href='Styles/jquery-ui-1.8.13.custom.css' rel='stylesheet' 
                                                type='text/css' />
</asp:Content>

<asp:Content ID='BodyContent' runat='server' 
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit 
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <div class='collapsibleContainer' title='Example Collapsible Panel'>    
	<p>
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris 
	varius ullamcorper lacus, ac pharetra libero commodo eu. Aenean auctor 
	imperdiet libero, sit amet scelerisque lorem placerat quis. Phasellus 
	pretium, lacus eget euismod cursus, nunc nibh semper urna, at blandit 
	elit nisl non dui. Sed blandit dignissim tellus, in egestas orci 
	facilisis vel. Curabitur consequat ante vel mauris accumsan rutrum. 
	Aliquam lorem est, ornare eget mollis sit amet, vestibulum et diam. 
	Phasellus cursus massa sodales metus luctus sed blandit quam rhoncus. 
	Proin nunc risus, scelerisque eu sagittis in, gravida vitae lectus. 
	Maecenas et ipsum ac mauris condimentum accumsan ac et ligula. 
	Phasellus mattis, tortor quis rutrum mollis, ante eros dictum 
	leo, ac venenatis augue nisl sit amet mauris. Maecenas cursus, arcu nec
	egestas molestie, leo lectus pellentesque sapien, eu sollicitudin urna 
	dolor vitae nisl. Proin lobortis, tortor quis congue lacinia, arcu elit
	consequat erat, vestibulum aliquet lorem massa sed leo. Suspendisse 
	volutpat odio in mauris cursus aliquam. Nullam sed sapien sit amet mi 
	laoreet sagittis. Integer rutrum lacus quis felis venenatis porta. 
	</p>
    </div>  
           
    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <script src='Scripts/jquery-ui-1.8.1.custom.min.js' 
	             type='text/javascript'>
    </script>
    <script src='Scripts/diQuery-collapsiblePanel.js' 
	             type='text/javascript'>
    </script>
    <script type='text/javascript'>
        $(document).ready(function () {
            $('.collapsibleContainer').collapsiblePanel();
        });
    </script>                         
</asp:Content>


In the example above the collapsable dic contains a text paragraph but try it with ASP.NET controls and you’ll find it works the same way.

Have fun !


Replacing the Animation Control Extender with jQuery Animations

Next up in this series is control animation.  The Ajax Control Toolkit has an Animation Control Extender [ see HERE ].

jQuery has animation built-in to its code [ see HERE ]

Basically, with jQuery animation you can animate any DOM object that you are access pragmatically.

Understand that animation is a huge subject and the variety of effects you can accomplish with jQuery animation is limited only by your imagination. One could write an entire book on jQuery animation and I’m not a “designer”.

I’ll show you a basic animation to get you started.

Here is the animation behavior I want.

Click on the image for a short video that shows the animation.

Here is the entire ASPX page.

Note that the positioning of the Button control is absolute and, for the sake of a simple demo, I’ve just hard-coded the position to work with a 1024×768 resolution. In production I’d have to dynamically determine the correct starting position.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master' 
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1.js' type='text/javascript'></script>
    <style> 
    .block  { 
        position:absolute; 
        background-color:#abc; 
        border-top-width: medium;
        left:30px; 
        width:90px; 
        height:90px; 
        margin:5px;
        top: 280px;
        } 
    </style> 
</asp:Content>

<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>jQuery has rich Animation.</h2>
    <p>
        <asp:Label ID='ResultLabel' runat='server' Text='&nbsp;'>
		</asp:Label><br />
    </p>
        
    <button id='left'>"</button> <button id='right'>"</button><br /> 
    <asp:Button ID='AnimatedButton' class='block' runat='server' 
	            Text='ASP Button' 
                ClientIDMode='Static' onclick='AnimatedButton_Click' />
    <br /><br /><br /><br />&nbsp;SECRET !
    <script type='text/javascript'>
        $('#right').click(function () {
            $('.block').animate({ 'left': '+=150px' }, 'slow');
        });

        $('#left').click(function () {
            $('.block').animate({ 'left': '-=150px' }, 'slow');
        }); 
 
    </script> 

</asp:Content>

By now (assuming that you have been following this series) you are starting to get comefortable with jQuery so the code should be pretty understandable. I’m simply using a selector to get the Botton Object by it’s class association (take note of the ClientId setting on the ASP.NET Button control) and calling the .animate method.

You can check out the documentation for all the available options here : http://api.jquery.com/animate/

Since I’m somewhat “creativly challenged”, here are some additional resources to help you get started with animation ideas.

Working with the $(this) object in jQuery

I’m working on an HTML application. It’s a Workout Timer and will become an HTML5 experiment that is “desktop deployable” and will store user profiles using HTML5 local storage, etc.

Though the application is in the very early stages, I know where I’m going and I want everything to be highly configurable, and for those customizations to be savable by the user.

Using the following prototype code I’m displaying a “stop watch” type display.


<!DOCTYPE html>
<html>

<head>
<meta content='en-us' http-equiv='Content-Language'>
<style type='text/css'>
    
 .fighttimer {
     text-align: center;
     padding: 5px;
     width: 96%; 
    }

</style>

<script type='text/javascript' src='js/jquery.js'></script>
<script type='text/javascript' src='js/jquery.fighttimer.js'></script>

</head>

<body>

<table class='fighttimer '>
    <tr>
        <td>&amp;nbsp;</td>
        <td>&amp;nbsp;</td>
    </tr>
    <tr>
        <td class='timecountdown'>00:00</td>
        <td>00</td>
    </tr>
    <tr>
        <td>
        <input type='button' class='timestart' value='Start' />
        <input type='button' class='timestop' value='Stop' />
        <input type='button' class='timereset' value='Reset' />
        </td>
        <td>&amp;nbsp;</td>
    </tr>
</table>

<script type='text/javascript'>
    $(function() {
        $('.fighttimer').fighttimer();
    });
</script>
    
</body>
</html>


I’m using a table for layout because I want all the features of the timer to be displayed in a grid and dynamically resizable by the end user.

Each part of the User Interface will be manipulated in JavaScript code.

Note in the markup above the inclusion of a JavaScript file on line $17 in which we define a jQuery plugin for our Timer Application.

Note also here JavaScript code block starting on line #42 where we wire up our custom plugin to elements whose class is “fighttime”.

In our case this is a single table object.

Read the rest of this entry »

Unobtrusive JavaScript in your ASP.NET pages.

One of the fundamental premises of ASP.NET is the “separation of concerns”. In ASP.NET WebForms Code and Markup go in separate files by default (.aspx / .aspx.cs). In ASP.NET MVC concern isolation is innate to the MVC convention. It therefore only makes sense to apply the same organizational construct to our use of JavaScript, especially as we federate more and more logic to the client side of our applications (meaning the browser.)

I’ve adopted  the practice of “Unobtrusive JavaScript” that appears below. FOr the sake of simplicity I’ve created this without using the standard WebForms template.

Lets suppose I have a page and I want to implement some jQuery / jQuery UI  features. Given this page …

I want to be able to drag & drop ….

And resize it ….

And I wanted to use jQuery UI features like a Pop-Up Calendar Picker.

Read the rest of this entry »

Calling Web Service Page Methods with jQuery

A “Web Service”, according to Wikipedia, is any software that is meant to provide computer to computer communication but is typcally comveyed using HTTP.

Just with the Microsoft Development stack there are lots of ways to expose application logic via HTTP.

  • ASMX
  • WCF
  • CSHTML
  • MVC
  • ASHX (ASP.NET Handler)
  • etc..

As we increase our client side user experience we will certainly be adding cient side behaviors with JavaScript, CSS, and in the future HTML5.

As we add dynamic behavior to our web application user interfaces, we’ll be updating the browser stsate with data retrieved by our client side code.

Often , the server side logic that will delivger this code will have no contextual value outside the “Web Page” that calls it.

Enter ASP.NET Page Methods. “Page Methods” live inside an ASP.NET page. They are callable via JavaScript and therefore require no seperate file, endpoint or infrastructure.

Since I (and many of you) have adopted jQuery as your client side development model, and since Microsoft has officially embraced jQuery, I’ve been moving all my new AJAX code to jQuery.

Since a first stab at calling page methods using jQuery syntax might be a bit tricky, I”ve created this demo.

Joel Carlson blogged a sample using an interesting Page Method Factory and I’m using that method (and code) in this demo.

Starting with the standard ASP.NET Web Forms web site template I’ve addede two page methods, one that is “Read Only” (no parameters) and one that sends data and recieves a return value.
Read the rest of this entry »

3 Articles on JavaScript Performance

I stumbled upon a 3 article series on JavaScript Performance that the IE Team has published and thought I’d share it:

  1. IE + JavaScript Performance Recommendations – Part 1
  2. IE + JavaScript Performance Recommendations – Part 2
  3. IE + JavaScript Performance Recommendations – Part 3

jQuery Confirm Buttons and Dialogs for ASP.NET

The ASP.NET Ajax Control Toolkit includes an “Confirm Button” control extender.
In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery and in this post I’ll address the “Confirm Button Extender”.
You might think that doing this is so trivial that it wouldn’t warrant a blog post but there is more to it that you might guess at first glance.
In ASP.NET WebForms there is a definite abstraction of the underlying web application mechanics and, for the purposes of this subject there some issues we must consider.
  1. By default, ASP.NET WebForms is a SERVER side programming model and therefore all UI elements (ASP.NET Controls) with user interactions are assumed to have server-side logic.
  2. We are integrating Client AND Server Development Models.
  3. An ASPX (Web Forms) page is assumed to contain only ONE HTML form. (Though we can use advanced manual techniques to bypass this limitation)
  4. Given the above items 1 & 3, all <asp:button> controls render as HTML Submit elements.
So what does that mean ?
HTML actually has three button types :
  • <INPUT TYPE=BUTTON> // A button with a click event.
  • <INPUT TYPE=SUBMIT> // A button whose click posts the html form
  • <INPUT TYPE=RESET> // A button that causes form fields to be reset
So, ASP.NET Buttons all render to HTML SUBMIT buttons.
We can divide button triggered dialogs into two groups:
  • Ones that display something but have no need to SUBMIT The form
  • Ones that take user input and MIGHT submit the form.
Perhaps the most straight forward way to implement both of these categories of button click dialogs is to use input type=”button” for all our buttons and programmatically submit the form when appropriate.
I’ve created a collection on customized buttons with OnClick dialogs:
Each of these will implement different usages of the jQuery.Alert plugin you can find [ HERE ]
The first button is wired to an information only dialog that will display for (in our case) 3 seconds.
Lets look at the markup, the CSS and the page specific JavaScript and then we’ll enumerate the rest of the button behaviors.
The Markup looks like this :

<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='Styles/jqdialog.css' rel='stylesheet' type='text/css' />
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
<br />
<button ID='btnotify' type='button' class='CustomButton'>
        Notification Popup
</button><br /><br />
<button ID='btalert' type='button' class='CustomButton'>
        Alert Popup
</button><br /><br />
<button ID='btconfirm' type='button' class='CustomButton'>
        Confim Dialog
</button><br /><br />
<button ID='btprompt' type='button' class='CustomButton'>
        Input Prompt
</button><br /><br />
<button id='btcontent' type='button' class='CustomButton'>
        Any Custom Content
</button><br /><br />

<script src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js'
        type='text/javascript'></script>
<script src='Scripts/jqdialog.min.js' type='text/javascript'></script>
<script src='Scripts/jQueryDialogs.js' type='text/javascript'></script>
</asp:Content>

Note that the concise markup does not reflect the rich functionality associated with the buttons.
The CSS class designation [class="CustomButton"] is responsible for the styled appearance of the buttons but not the behavior. Often when using jQuery we will use a data attribute or a class identifier to connect the desired jQuery code to the HTML elements but since button dialogs are likely to be very specific (one dialog for each button), the jQuery behaviors in this demo will be connection via the button element ID.
The CSS is as follows. Note that the Custom Button class is at the bottom and all the rest of the CSS defines the visuals for the various dialogs. In your app you would only include the classes that you use on your pages.

Using jQuery for ASP.NET Styled DropDown

The ASP.NET Ajax Control Toolkit includes an “Styled Dropdown” control extender.
In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery.

HTML has the <select> element for drop down lists and ASP.NET has the DropDownList control, but the styling is pretty plain.

Luckily, we can us a jQuery plugin to change the styling of both <select> and <asp:DropDownList>
By default the DropDownList looks like this:

While this works fine we might want to style the DropDown to match our UI of to obviate the context of our dropdown.

You can find the plugin we will use here:
The custom styling will consist of a combination css and the following background image.

The page markup is as follows:

<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <link href='Styles/Selectbox.css' rel='stylesheet' type='text/css' />
	<script src='http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.5.1.js'
            type='text/javascript' charset='utf-8'></script>
	<script type='text/javascript' src='Scripts/jquery.selectbox-0.5.js'>
	</script>
    <script src='Scripts/PageScript.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>

    <p>
    <asp:DropDownList runat='server' name='Items' id='Items'
                      class='StyledDD' ClientIDMode='Static'>
      <asp:ListItem>One</asp:ListItem>
      <asp:ListItem>Two</asp:ListItem>
      <asp:ListItem>Three</asp:ListItem>
      <asp:ListItem>Four</asp:ListItem>
    </asp:DropDownList>
    </p>
</asp:Content>

Read the rest of this entry »

Using jQuery for ASP.NET Textbox Autocomplete

The ASP.NET Ajax Control Toolkit includes an “Autocomplete Extender“.

In this series I’ve been demonstrating ways to implement the features of the MS Ajax Toolkit with jQuery.

jQuery UI makes “AutoComplete” very straight forward (Read the plugin spec here.)

Here is the behavior.

After the user enters 2 or more characters, then the UI starts to suggest values for the textbox.

In the case fo the jQuery UI Autocomplete plugin, the data can come from inside the page’s Document Object Model (DOM) or from a JavaScript callable web service.

For small data sets you may want to just send all the possible values to the browser with the rest of the page but AutoSuggest fields are most helpful when the number of possible value choices are too numerous to fit in a page’s dropdown control.

In this case, supplying the values via a service method is your choice and that’s what we’ll do in our example.

After creating a new website using the default ASP.NET Web Site Template, I’ll include a jQuery UI template CSS file and 3 JavaScript files.

  • jQuery
  • jQuery UI
  • a custom JavaScript file that contains my page specific code.

Then I’ll add an ASP.NET TextBox filed and associated label for the user to enter an email address in.

The markup for my default.aspx page is as follows:


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		                        Inherits='_Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='http://ajax.aspnetcdn.com/ajax/jquery.ui/
                   1.8.10/themes/redmond/jquery-ui.css'
      rel='stylesheet' type='text/css'/>

</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
                              ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <hr /><br />

    <div>
            <label for='tbAuto'>Enter Email: </label>
             <asp:TextBox ID='tbAuto' class='autosuggest' runat='server'>
             </asp:TextBox>
    </div>
    <script type='text/javascript'
            src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js'>
    </script>
    <script type='text/javascript'
     src='http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js'>
    </script>
    <script src='Scripts/PageScript.js' type='text/javascript'></script>
</asp:Content>

Next we need a service that will take a few characters of string as in input argument and return a collection of emaill addresses that match the beginning characters that the user entered.

SO, I’ll add an .ASMX service called EmployeeList.asmx

The service codebehind looks like this:



using System.Collections.Generic;
using System.Linq;
using System.Web.Services;
using System.Web.Script.Services;

[WebService(Namespace = &quot;http://tempuri.org/&quot;)]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class EmployeeList : System.Web.Services.WebService
{
  [WebMethod]
    public List GetEmailSuggestions(string mail)
    {
    var emp = new Employee();
    var suggestionList = emp.GetEmployeeList()
    .Where(m => m.Email.ToLower().StartsWith(mail.ToLower()));
        return suggestionList.ToList();
    }
}

If you are new to service programming in ASP.NET you will note the [WebMethod] attribute on the GetMailSuggestions method will cause the method to be exposed via HTTP and the class itself is decorated with the [ScriptService] attribute which will make the class callable my JavaScript and provide facilities like JavaScript proxy generation.
Read the rest of this entry »

A jQuery Combo Box for ASP.NET

The ASP.NET Ajax Control Toolkit contains a Combo Box Control.

Since I’m posting a series on replacing Ajax Control Toolkit functions with jQuery, in this post we’ll use a jQuery plugin to DropDown control into a slick ComboBox.

Here is the experience :

You can click on the down arrow and see the entire list. Combo boxes excel in scenarios where there are MANY items in the selection set. (Usually to many to be seen without scrolling.

So  in a Combo Box we can type to filter the selection list based on what is types.

Since this is an ASP.NET control, when we submit the page we can access the selected value in our code-behind.

I’m building this using a jQuery Plugin called Hyjack.

[ Get it HERE ]

As with most jQuery plugins, Hyjack is simple to use.

NOTE: the code below includes all JavaScript code at the TOP of the page, uses in line JavaScript, and statically includes the jQuery library. This is done only for illustrative simplicity and is NOT best practice. Please find a variety of best practices information in the posts HERE.

Here is the complete page markup:



<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeBehind='Default.aspx.cs'
         Inherits='jQueryComboBox._Default' %>

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <link href='Styles/hyjack.css' rel='stylesheet' type='text/css' />
    <script src='Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'>
	</script>
    <script src='Scripts/jquery.hyjack.select.js' type='text/javascript'>
	</script>
    <script type='text/javascript'>

		$(function () {

			// Hyjack Onload with all defaults
			$('.hyjack').hyjack_select();

			/* Multiple CLASS with customization

			$('.hyjack').hyjack_select({        // Defaults
			ddImage: 'image/of/arrow.png',      // arrow_down.png
			ddCancel: 'image/of/cancel.png',    // cancel.png
			ddImageClass: 'class_of_arrow',     // hjsel_ddImage
			ddCancelClass: 'class_of_cancel',   // hjsel_ddCancel
			emptyMessage: 'No Items Message',   // No Items to Display
			restrictSearch: false/true,         // false
			offset: 12                          // false
			});

			*/
        });
	</script>

</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Select Your State
    </h2>
    <br /><br />
    <asp:DropDownList ID='DDPickState'  class='hyjack' runat='server'>
        <asp:ListItem Value='AL'>Alabama</asp:ListItem>
        <asp:ListItem Value='AK'>Alaska</asp:ListItem>
        <asp:ListItem Value='AZ'>Arizona</asp:ListItem>
        <asp:ListItem Value='AR'>Arkansas</asp:ListItem>
        <asp:ListItem Value='CA'>California</asp:ListItem>
        <asp:ListItem Value='CO'>Colorado</asp:ListItem>
        <asp:ListItem Value='CT'>Connecticut</asp:ListItem>
        <asp:ListItem Value='DC'>District of Columbia</asp:ListItem>
        <asp:ListItem Value='DE'>Delaware</asp:ListItem>
        <asp:ListItem Value='FL'>Florida</asp:ListItem>
        <asp:ListItem Value='GA'>Georgia</asp:ListItem>
        <asp:ListItem Value='HI'>Hawaii</asp:ListItem>
        <asp:ListItem Value='ID'>Idaho</asp:ListItem>
        <asp:ListItem Value='IL'>Illinois</asp:ListItem>
        <asp:ListItem Value='IN'>Indiana</asp:ListItem>
        <asp:ListItem Value='IA'>Iowa</asp:ListItem>
        <asp:ListItem Value='KS'>Kansas</asp:ListItem>
        <asp:ListItem Value='KY'>Kentucky</asp:ListItem>
        <asp:ListItem Value='LA'>Louisiana</asp:ListItem>
        <asp:ListItem Value='ME'>Maine</asp:ListItem>
        <asp:ListItem Value='MD'>Maryland</asp:ListItem>
        <asp:ListItem Value='MA'>Massachusetts</asp:ListItem>
        <asp:ListItem Value='MI'>Michigan</asp:ListItem>
        <asp:ListItem Value='MN'>Minnesota</asp:ListItem>
        <asp:ListItem Value='MS'>Mississippi</asp:ListItem>
        <asp:ListItem Value='MO'>Missouri</asp:ListItem>
        <asp:ListItem Value='MT'>Montana</asp:ListItem>
        <asp:ListItem Value='NE'>Nebraska</asp:ListItem>
        <asp:ListItem Value='NV'>Nevada</asp:ListItem>
        <asp:ListItem Value='NH'>New Hampshire</asp:ListItem>
        <asp:ListItem Value='NJ'>New Jersey</asp:ListItem>
        <asp:ListItem Value='NM'>New Mexico</asp:ListItem>
        <asp:ListItem Value='NY'>New York</asp:ListItem>
        <asp:ListItem Value='NC'>North Carolina</asp:ListItem>
        <asp:ListItem Value='ND'>North Dakota</asp:ListItem>
        <asp:ListItem Value='OH'>Ohio</asp:ListItem>
        <asp:ListItem Value='OK'>Oklahoma</asp:ListItem>
        <asp:ListItem Value='OR'>Oregon</asp:ListItem>
        <asp:ListItem Value='PA'>Pennsylvania</asp:ListItem>
        <asp:ListItem Value='RI'>Rhode Island</asp:ListItem>
        <asp:ListItem Value='SC'>South Carolina</asp:ListItem>
        <asp:ListItem Value='SD'>South Dakota</asp:ListItem>
        <asp:ListItem Value='TN'>Tennessee</asp:ListItem>
        <asp:ListItem Value='TX'>Texas</asp:ListItem>
        <asp:ListItem Value='UT'>Utah</asp:ListItem>
        <asp:ListItem Value='VT'>Vermont</asp:ListItem>
        <asp:ListItem Value='VA'>Virginia</asp:ListItem>
        <asp:ListItem Value='WA'>Washington</asp:ListItem>
        <asp:ListItem Value='WV'>West Virginia</asp:ListItem>
        <asp:ListItem Value='WI'>Wisconsin</asp:ListItem>
        <asp:ListItem Value='WY'>Wyoming</asp:ListItem>
    </asp:DropDownList>
    <br /><br />
    <asp:Button ID='ButtonSubmit' runat='server' Text='Submit'
        onclick='ButtonSubmit_Click' /><br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>
</asp:Content>

And here is the code behind.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace jQueryComboBox
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }

        protected void ButtonSubmit_Click(object sender, EventArgs e)
        {
            LabelResult.Text = &quot;The State You Picked is : &quot; +
                                DDPickState.SelectedValue.ToString();
        }
    }
}

I’ve statically defined the list items but since the parrent control is an ASP.NET Drop Down, you could easily bind the items list to a data source of your choosing.

[ You can download the code above HERE ]


Improving the Code – jQuery Modal Dialog in an ASP.NET page.

Last month I did this post on creating a jQuery Modal Dialog in an ASP.NET page.

My friend Jose Guay emailed me to say “hey Joe – nice sample but why not really wire things up the jQuery way ?”

Jose’s right so here it is.

The OLD markup looked like this:


<asp:Content ID='HeaderContent' runat='server'    
             ContentPlaceHolderID='HeadContent'>
    <link href='Scripts/fancybox/jquery.fancybox-1.3.4.css'
          rel='stylesheet' type='text/css' />
    <script src='Scripts/fancybox/jquery.fancybox-1.3.4.js' 
	        type='text/javascript'>
    </script>
    <script src='Scripts/tos.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server'  
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <div id='content'>
	<h1>Join Our Community</h1>
	<hr />
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
	Etiam quis mi eu elit tempor facilisis id et neque.
	Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
	Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet
	ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
	vehicula non pretium varius, cursus ac tortor. Vivamus fringilla 
	laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
	Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
	aliquet tempus sem, id aliquam diam varius ac.
    <hr />
    <br />
    <!-- Modal Dialog -->
    <a id='tos' href='#serviceterms' 
	   title='You must agree with our tems of service.'>
       Click HERE to Agree to our Terms
    </a>
    <div style='display: none;'>
	<div id='serviceterms' style='width:440px;height:250px;overflow:auto;'>
		Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
		Etiam quis mi eu elit tempor facilisis id et neque.
		Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
		Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras 
		ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
		vehicula non pretium varius, cursus ac tortor. Vivamus fringilla 
		laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
		Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
		aliquet tempus sem, id aliquam diam varius ac.
		<br /><br /><hr />
		<input type='button' value='Yes' onclick='ToS_Agree()' />&nbsp;&nbsp;
		<input type='button' value='No' onclick='ToS_NotAgree()' />
	</div>
	</div>
    <br /><br />

    <asp:Button ID='SubmitButton' runat='server' Text='Submit Form' 
	            Enabled='False'
                ClientIDMode='Static' onclick='SubmitButton_Click' />
        <br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>

</div>
</asp:Content>

And the included JavaScript (tos.js) looked like this:


$(document).ready(function () {

    $('#tos').fancybox({
    	'titlePosition': 'inside',
    	'modal': 'true',
    	'transitionIn': 'none',
    	'transitionOut': 'none'
    });
});

function ToS_Agree() {
    $('#SubmitButton').removeAttr('disabled');
    $.fancybox.close();
}

function ToS_NotAgree() {
    $('#SubmitButton').attr('disabled', 'disabled');
    $.fancybox.close();
}

So, I am sort of mixing metaphor’s here.

Lets look at a better way.

Read the rest of this entry »

Running JavaScript when the Web Page loads.

From HTML body onload to jQuery Factory Function Shorthand


As you continue implement user interface logic in your Web Application you’ll be coding in JavaScript and you’ll eventually encounter a scenario where you want to execute some JavaScript code when your web page is loaded. Working with jQuery you’ll discover this scenario immediately.

One of my teammates was asking be about web page loading events and jQuery Syntax so I though others might benefit from an explanation of the onload / ready syntax as well as an example of jQuery shorthand.

The native way of doing this is to wire up an event handler (function) for the onload event of the html element.


<!DOCTYPE html>
<html>
<head>

<script type='text/javascript'>
 function SomeFunction() {
 alert('I was run at startup !');
 }
</script>

<title>Sample Page</title>

</head>

onload='SomeFunction()'>
   My Web Page !
</body>

</html>

This works, but it’s not perfect.

Read the rest of this entry »

A jQuery Color Picker for ASP.NET Apps

There are lots of “ColorPickers” out there.

I liked the way mColorPicker worked, though did make some minor modifications to the source for this demo.

Just picking a color is a bit boring so I’m adding a bit of spice.

  1. After selecting a new color client side I use that color to change the background color of the current page (no postback)
  2. Upon Server PostBack we echo the hex value of the selected color.

Here is the experience.


Note the TextBox which is an ASP.NET TextBox Server Control and the multi-color icon nect to the text box.

Clicking on the color icon displays the ColorPicker.

As you hover over the different colors the hex value of the current color is displayed in the TextBox and the TextBox background color is set to that color as well.

The “Set Color” Button is an HTML input element (Client Side) and when you click it, the background color of the page is set to the newly selected color (as you can see in the image above.)

The “Submit Form” Button is an ASP.NET Server Side Button Control and when you click it the form is posted back to the server.

The new color value is retrieved from the Color Text Box and is inserted into the Label control at the bottom of the page.

Note that after the page is submitted (and therefore redrawn) the page’s background revert to its default color. If you wanted to make the selected color permanent we would need to dynamically load the background color from somewhere and save the updated color whenever the user selected a new one.
Feel free to give that a try on your own if you need such a feature.

To implement this, begin by loading the jQuery and jQueryUI libraries.

I’ll do this in my MasterPage and load them from the Microsoft CDN (which means you’ll have to modify the following code if want to run this on a machine that is not connected to the internet.)


<script type="text/javascript" 
        src="http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.js"></script>
<script type="text/javascript" 
        src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.10/jquery-ui.js">

The actual page markup look like this.
Read the rest of this entry »

A Collapsible Content Area Using jQuery UI

As I’m going though all of the Ajax Control Toolkit Controls and demonstrating ways to replace the behaviors with client side technology (JavaScript / jQuery) I can’t help but wonder if some of them are too simple to bother with but since I committed to blogging one example for each control in the ACT, I will continue and then move on to more “Ajax and UI Patterns” content.

I did a previous post on implementing an Accordion style Content Container using jQueryUI and thereby replacing the Accordion Control in the Ajax Control Toolkit.

I suppose you could use the Accurdion method that I demonstrated in that post and only use one accordion section but there is an even easier jQueryUI plugin that you can use. Check put the Simple Collapsible Panel plugin HERE.

If you have tried a number of jQuery UI Plugins using the default ASP.NET Web Site Template and ASP.NET Server controls you have probably discovered that it’s possible to discover conflicts.

Lets try it with ths Collapsible Panel Plugin.

We’re going to need jQuery and jQueryUI which I will include as follows.


<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='Styles/diQuery-collapsiblePanel.css' rel='stylesheet' 
            type='text/css' />
<link href='Styles/jquery-ui-1.8.11.custom.css' rel='stylesheet' 
            type='text/css' />
<script src='Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'>
</script>
<script src='Scripts/ui/jquery-ui-1.8.11.custom.js' type='text/javascript'>
</script>
<script src='Scripts/diQuery-collapsiblePanel.js' type='text/javascript'>
</script>
    <script type='text/javascript'>
            $(document).ready(function() {
                  $('.collapsibleContainer').collapsiblePanel();
              });
    </script>
</asp:Content>

Now, for demo simplicity there are a few things above that you probbaly do not want to do in a production application.

  1. I used the default version of jQuery that is part of the default ASP.NET project template. You should use the LATEST version of jQuery.
  2. You probably want to load jQuery from the Microsoft CDN
  3. You also probbaly want to load jQueryUI from the Microsoft CDN
  4. It’s good practive to put all your JavaScript code in a .js file
  5. Whenever possible you want to reference your JavaScript files from the bottom of your page markup. [ Read HERE ]

Read the rest of this entry »

jQuery Modal Dialog in an ASP.NET page.

Modal dialogs are a cornerstone of modern application user interface design and web applications don’t differ from any other type of application UI in this regard.
I did a JavaScript & jQuery Modal Dialogs Roundup a little while back and though I listed a bunch, readers even added a few more. So, there are lots of options.
People seem to get freaked out about making choices. Personally I like the fact that I have so many options and, in the case of Modal Dialogs for web applications, I can pick one that most closely matches the aesthetics and behaviors that I want for my application.
For this post I’m going to use http://fancybox.net/
Which one YOU choose shouldn’t materially change your implementation strategy since, as I hope is starting to become clear, the tricky part in using these sort of jQuery features is the relationship between client side “stuff (HTML Elements, JavaScript, Data, etc.) and the ASP.NET specific things.
Next lets add the jQuery library to our masterpage.
Normally for demo code I use the static librraies that get added to my site directory by VIsual Studio, but in a prodocution wed site you probbaly want to use the Microsoft CDN.
Like this :

<head runat='server'>
    <title></title>
    <link href='~/Styles/Site.css' rel='stylesheet' type='text/css' />
    <script src='http://ajax.aspnetcdn.com/ajax/jquery/jquery-1.5.1.js'
            type='text/javascript'></script>
    <asp:ContentPlaceHolder ID='HeadContent' runat='server'>
	</asp:ContentPlaceHolder>
</head>

Why use the CDN you say?
  • The CDN has the latest released versions. The Visual Studio template has the version that was current back when Visual Studio 2010 was released.
  • Many ASP.NET sites use jQuery and load from the Microsoft CDN – the files may already be cached for your user.
  • If if the files are not cached it will likely be a bit faster.
  • Take load of YOUR server and reduce your server’s bandwidth.
The page that will display our Modal Dialog pulls in the FancyBox JavaScript and CSS files as well as our own custom JavaScript file that defines the client behavior we desire.
For learning simplicity I’ve previously implemented our custom JavaScript in-line but in practice, it’s better to abstract or JavaScript.
Now that we are getting familiar with the jQuery basics I’ll be trying to use more “best practices” in the demo code as I continue with the jQuery series.

<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <link href='Scripts/fancybox/jquery.fancybox-1.3.4.css'
          rel='stylesheet' type='text/css' />
    <script src='Scripts/fancybox/jquery.fancybox-1.3.4.js' 
	        type='text/javascript'>
    </script>
    <script src='Scripts/tos.js' type='text/javascript'></script>
</asp:Content>

Our scenario is that the Modal Popup is a “Terms of Use” dialog.
Here is our page’s markup.


<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <div id='content'>
	<h1>Join Our Community</h1>
	<hr />
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
	Etiam quis mi eu elit tempor facilisis id et neque.
	Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
	Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet
	ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
	vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue
	laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
	Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
	aliquet tempus sem, id aliquam diam varius ac.
    <hr />
    <br />
    <!-- Modal Dialog -->
    <a id='tos' href='#serviceterms' 
	   title='You must agree with our tems of service.'>
        Click HERE to Agree to our Terms
    </a>
    <div style='display: none;'>
	<div id='serviceterms' style='width:440px;height:250px;overflow:auto;'>
	Lorem ipsum dolor sit amet, consectetur adipiscing elit. <br /><br />
	Etiam quis mi eu elit tempor facilisis id et neque.
	Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare.
	Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet
	ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum,
	vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue
	laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in.
	Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc
	aliquet tempus sem, id aliquam diam varius ac.
	<br /><br /><hr />
	<input type='button' value='Yes' onclick='ToS_Agree()' />&nbsp;&nbsp;
	<input type='button' value='No' onclick='ToS_NotAgree()' />
	</div>
	    </div>
    <br /><br />

    <asp:Button ID='SubmitButton' runat='server' Text='Submit Form' 
	            Enabled='False'
                ClientIDMode='Static' onclick='SubmitButton_Click' />
        <br /><br />
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>

</div>
</asp:Content>

Note the buttons on lines 39 and 40. We want our Modal Dialog to “actionable” in that the user must click YES to accept the terms of service or NO to reject them.
In order to submit the form the user must accept the terms of service. The submit button declared at line 45 is DISABLED by default to the form can’t be submitted.
When the user clicks on the “YES” button inside the Modal Dialog the button will be enabled.
Let’s look at our custom JavaScript.

$(document).ready(function () {

    $('#tos').fancybox({
    	'titlePosition': 'inside',
    	'modal': 'true',
    	'transitionIn': 'none',
    	'transitionOut': 'none'
    });
});

function ToS_Agree() {
    $('#SubmitButton').removeAttr('disabled');
    $.fancybox.close();
}

function ToS_NotAgree() {
    $('#SubmitButton').attr('disabled', 'disabled');
    $.fancybox.close();
}

We also have a bit of C# Code-Behind that does two things.

Using jQuery UI DatePicker in an ASP.NET Application.

The Ajax Control Toolkit contains a Calendar Control.

jQuery UI has an amazing alternative in the DatePicker control.

When it comes to this and all jQueryUI features, do yourself a service and check out the tabs – Overview, Options, Events, Methods, Theming. In the case of the DatePicker control, not only are all the expected events exposed and hookable but the rich Options collection will let you exercise detailed control over the date and UI formatting.

If you’re new to jQuery UI you will note that when you download the jQueryUI you can select one of a collection of preexisting themes.

Let’s begin by walking through the process of getting the jQueryUI library.

Start by hoping over to http://jqueryui.com/

We need to select a theme to use for configuring our jQueryUI download, so click on the “Demos & Documentation” link at the top of the page.

AT the top right corner of the demo area of the page there is drop-down with theme previews. Select a theme to try and then run the demos to see how that particular feature looks using the selected theme.

In our case we’ll select the Redmond Theme.

Now, go to the download page.

Read the rest of this entry »

JavaScript & jQuery Modal Dialogs Roundup

As I’ve been showing ways to use jQuery and JavaScript instead of the Ajax Control Toolkit, or just integrate client side code with ASP.NET I’ve reviewed a collection of requests for Modal Dialog samples.

While I’m working on one I thought I’d post a list of existing options that I’ve found.

Note that I have intentionally omitted ones that seemed to be image focused and only included the ones that had a broader custom application value.

Feel free to post others that you think merit consideration in the comments section !


Nyro Modal

The demo is not as pretty as some of the others but don’t let that fool you. This one is feature rich for developers.


jQuery Tools Overlay

Overlay is just one of the features in the jQuery Tools “Suite”. It’s really a whole UI package for jQuery.


jqModal

Described as minimalist but feature rich and easy to style with support for many features including events, callbacks and nested dialogs.


Read the rest of this entry »

What JavaScript Library or Framework do you use ?

Sorry – This Poll is Closed!


An “Always Visible” area with JavaScript

The Ajax Control Toolkit has an “Always Visible” Extender.

I’ve been working on finding / writing / showing client side alternatives to the Ajax Control Toolkit features.

As I examine ths useage of such a feature it seems that the needs of the specific usage scenarios.

Rick Strahl wrote a great one HERE that implements a cliet side status bar.

I wanted one that sort of looks like the Ajax Control Toolkit one.

Since I still don’t yet “think” in jQuery this plain old JavaScript and I’ll look to converting it to a jQuery plugin at some point in the future.

So, here is the experience ….

And then after scrolling down the page.

Read the rest of this entry »

BOOK: Eloquent JavaScript

For years I’ve said “JavaScript is inevitable”.  More and more all web developers are needing to add richness to their Web UIs and their UI Interactions.

The thing about Scripting Languages is that folks tend to learn by trial and error. There is nothing wrong with this, it’s how I learned JavaScript.

But, writing Client Side & Server Side code together can be tricky. I very frequently get email from customers experiencing a debugging problem whose answer is fund in confused or incorrectly mixed Client / Server coding.

So, writing good, clean MODERN JavaScript is not only important to but a service to anyone who will need to crack open your code in the future to make enhancements (including the original author).

So I got this book. “Eloquent JavaScript – A Modern Introduction to Programming”.

This is a great book except for the subtitle. Since it’s called an introduction, folks that have some JavaScript experience might pass this book up and that would be a shame.

I found it not only a tutorial but a style guide.

Coverage includes, Data Structures, Object Oriented JavaScript Programming, Functional Programming, Modularity, the DOM, HTTP Requests, as well as all the basics of JavaScript.

I encourage you to check it out [ HERE ]


JavaScript Auto Positioned Popup

Next up in this series on replacing the Ajax Control Toolkit functionality with client side logic is the ACT PopUp control extender.

I have to admit that I stumbled a little on this one.

Here are the examples provided by the Ajax Control Toollkit demo site.

One sample is a multi-select, but this usage seems unecessary. I’d just use a drop down.

Another was this calendar pop-up,but for this I would use one of the plethora of Date Selector controls that are available out three.

Still, there is a scenario where the user could benefit from some field specific associated data (but a lot more than a tool-tip.)

So I decided to implement a Pop-Up that shows a <div> element. Inside that div we can put anything. Markup, Client Side Controls, Server Side Controls, and JavaScript code (so if we wanted to we could put code in the pop-up that interacted with the corresponding DOM element that it was “Poped Up for”).

For such JavaScript to be reusable though, it needs to be responsible for its own positioning.

I’ve written this as plain old JavaScript. I plan in the near future to convert this to a jQuery Plugin.

Here’s what the finished code looks like in execution.

In the above screenshot I’ve bound a Pop-Up to the SECOND TextBox and when I click or tab into that TextBox the Pop-Up is displayed.

The JavaScript code automatically figures out where the TextBox is displayed and places the Pop-Up under the TextBox slightly indented.

Of course we want to make the feature as simple to call as possible.

Here is the markup that results in the above page.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
<link href='Styles/FieldPopUp.css' rel='stylesheet' type='text/css' />
<script src='Scripts/FieldPopUp.js' type='text/javascript'></script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>Welcome to ASP.NET!</h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' title='ASP.NET Website'>www.asp.net</a>.
    </p>
<br />
Text 1 - <input type=text id='t1'><br />
Text 2 - <input type=text id='targettextbox'
                onfocus='SetPopup('divtopop','targettextbox', 'S');'
                onblur='SetPopup('divtopop','targettextbox', 'H');'>
<br />
Text 3 - <input type=text id='t3'><br />
<div id=divtopop class='boxover'>
This Field <br />
<hr>
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,
when an unknown printer took a galley of type and scrambled it to make a type
specimen book. It has survived not only five centuries, but also the leap into
electronic typesetting, remaining essentially unchanged.<br /><br />
<div style='text-align: center;'>[ Hide ]</div>
</div>
</asp:Content>

Notice the OnFocus and OnBlur event handlers that call the SetPopUp JavaScript Function.

Doesn’t this syntax suddenly seem cumbersome after working with jQuery for even a short while?  Even though this is pretty simple to use it will still be more elegant when implemented as a jQuery Plugin so that we can apply the functionality via a jQuery selector.

The JavaScript is somewhat more complex.

Read the rest of this entry »

20 jQuery Accordion Container Choices and Examples.

jQuery UI Accordion - Offers themes and a rich collection settable options and events.

[ Get more info HERE ]


i-Marco’s Yet Another jQuery Accordion – Great for side-bar menus.

[ Get more info HERE ]


Stupid Simple jQuery Accordion – SUPER Simple Usage.

[ Get more info HERE ]


Lateral Code jQuery Accordion

[ Get more info HERE ]


Bassistance jQuery Accordion  Elegant Appearance

[ Fore more info click HERE ]


Read the rest of this entry »

Cascading DropDown with jQuery – WebMatrix Version

In this previous blog post I demonstrated implementing a Cascading Drop Down in ASP.NET WebForms using jQuery.

I had a couple of emails asking about the differences for using this technique in Microsoft WebMatrix so I thought I’d post a WebMatrix Version.

I also got a great email from Elijah Manor (@elijahmanor is an ASP.NET Insider & MVP) with some improvement suggestions.

Every code post on my blog finds someone out in web land who needs to tell me how they could write it better.

Elijah, however, is the Senior Architect at appendTo, THE jQuery company. I know really great developers that went to appendTo to learn jQuery training – hell I want to go take their jQuery Training.

Elijah is not only a really smart guy, he’s a really GOOD guy and emails not to show off but from a true desire to help – THANKS Elijah.

I’ve added some of Elijah’s suggested improvements and on his prompting will soon convert this code to my very first jQuery Plugin.

You’ll recall the Cascading Drop Down UI.


In the page template we’ll include a reference to the jQuery library.


        My ASP.NET Web Page - @Page.Title
        @RenderSection('header')

Note that , as Elijah suggests, I’m referencing the 1.5 (recent) version of the jQuery library via the Microsoft Content Delivery Network (CDN) Our WebMatrix page looks like this.

Read the rest of this entry »

ASP.NET Accordions with jQueryUI

Replacing the Ajax Control Toolkit’s Accordion control with jQueryUI

Accordion style containers are a great way to maximize the use of your browser based screen real estate.

Note the UI and behavior of an Accordion Content Control.

The default display looks like this.

Clicking on the second header bar closes the first content area and opens the second.

Some time ago I did a video on using Accordions with the ASP.NET AJAX Control Toolkit. You can check it out here.

The thing about accordion controls is the the content exists in HTML <div> elements which means we can populate them with static markup, server side controls, of even markup retrieved by way of an AJAX service method call and inserted by our client side JavaScript code.

There are many JavaScript libraries and jQuery Plug-Ins that can assist us in implementing an accordion container. In this case I’ll use one of the most popular, the jQueryUI library.

http://jqueryui.com/

jQueryUI is highly configurable as we’re about to see.

First, click the demos link.

Though we’re specifically interested in the Accordion demo, you should take time to look at the other demos to see some of the other things that can be accomplished with jQueryUI.

Note that after you load the Accordion demo you can try different color “themes” by using the themes selector on the left.

When you’ve decided which theme you are interested in using as a starting place you need to download jQueryUI.

Read the rest of this entry »

Dynamic Cascading Selection Lists for ASP.NET WebForms with jQuery.

I’ve blogged previously that I’m on a mission to build samples of implementing all the ASP.NET Ajax Control Toolkit Features WITHOUT the Ajax Control Toolkit.

If you’re ever used the Cascading Drop Down control extender in the Ajax Control Toolkit, then you know that it’s syntactically easy to use but a real pain to debug.

You may have also discovered that any JavaScript code that effects the state of an ASP.NET Drop Down Control has it’s influence lost when you submit your form back to the server.

This is due to a collection of tomfoolery that happens under the covers with the Drop Down control as it pertains to ASP.NET View State.

To side step the ViewState complexities, we’ll do all the Cascading Drop Down UI on the client and only use ASP.NET Server controls the minimal amount necessary to easily post our selected values back to the server.

Here is the UI interaction flow that we want.

This is the way that the page renders.

Then the user selects from the list of car Makes.

Note that at this point, ONLY the Car “Makes” list is populated.

We can’t display the models until we know what “Make” the user is interested in.

As a result, the “Models” and “Colors” controls are not even active yet.

After we select a car “Make”, the “Models” Drop Down has been filled with values as the result of an AJAX call to the server that passes the “Make” value as an argument so that the related “Models” can be returned.

The same happens when we select a “Model”.

The colors that the model is available in now appear in the “Colors” Drop Down.

When the user has selected a value in each of the three text boxes and clicks the Submit Button, the ASP.NET’ page’s Code-Behind Retreives the selected values and displays a result message.

There is, however, a but of trickery necessary to make this happen.

First, the Drop-Dwn lists are NOT ASP.NET Server Controls, they are simple HTML <select> elements.

This first one (Makes) is populated with statically defined values but you could populate them from a service call when the page loads if you felt it neccessary.

New car companies don’t come into existance very often, so I don’t think it’s necessary in this case.


    <div id='SelectionContainer' runat='server'>
    <select id='DDListMake' name='DDListMake' style='width: 200px'>
		<option>Select...</option>
		<option value='Ford'>Ford</option>
		<option value='Cadilac'>Cadilac</option>
		<option value='Toyota'>Toyota</option>
		<option value='Jeep'>Jeep</option>
		<option value='Mazda'>Mazda</option>
	</select>
    <asp:HiddenField ID='TextMake' runat='server' ClientIDMode='Static' />
    <br />
    <select id='DDListModels' style='width: 200px' disabled='true'></select>
    <asp:HiddenField ID='TextModel' runat='server' ClientIDMode='Static' />
    <br />
    <select id='DDListColors' style='width: 200px' disabled='true'></select>
    <asp:HiddenField ID='TextColor' runat='server' ClientIDMode='Static' />
    <br /><br />
    <asp:Button ID='ButtonSend' runat='server' Text='Submit Selections'
                onclick='ButtonSend_Click' />
    </div>
    <asp:Label ID='LabelResult' runat='server' Text=''></asp:Label>

Note that the Drop Down Lists are simple HTML Select Elements.

The Button and the Label are ASP.NET controls.

Take special note of the three “Hidden” ASP.NET contol instances.

We will populate these with the values that the user selects in each Drop Down so that we can retrieve those values in our code-behind.

Implementing the simplest possible web service.

The .NET platform is rife with ways to serve up content via HTTP.

We have ASMX, ASPX, ASHX, WCF, MVC Views, all of which could be used to serve non markup data.

Read the rest of this entry »

TextBox Input Watermark using jQuery

The Microsoft Ajax Control Toolkit (ACT) contains a TextBox Watermark control.

I did a sample and video HERE.

I’ve started to write samples to implement all the ACT features with jQuery (and jQuery plugins), you can read more HERE.

Here is the effect we’re looking for, a hint to the user as to the desired or required input (note this sampe doesn’t do input validation, we’ll do that in a later demo.)

To get this we’re going to use jQuery and the TinyWatermark jQuery plugin.

The effect is completely applied in our markup. There is no server side implementation.

I like this as I prefer to off load as much work as possible to the client machine.


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
                 AutoEventWireup='true' CodeFile='Default.aspx.cs' 
 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery-1.4.1-vsdoc.js' type='text/javascript'>
</script>
    <script src='Scripts/jquery_tinywatermark-3_1_0.js' 
        type='text/javascript'>
    </script>
    <style>
        .watermark
        {
        color:#999;
        background-color: #FFD4D4;
        font-style: italic;
        }
    </style>
    <script type='text/JavaScript'>
        jQuery(function ($) {
            $('.watermarked').watermark('watermark');
        });
    </script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
             ContentPlaceHolderID='MainContent'>
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit
        <a href='http://www.asp.net' 
		   title='ASP.NET Website'>www.asp.net</a>.
    </p>
    <p>
        Please enter your email address here ......<br />
        <input type='text' class='watermarked' size='50'
                  title='Enter Email Address here...' />
    </p>
</asp:Content>

Note that in the “HeadContent” placeholder I pull in jQuery and the TinyWatermark jQuery Plugin. (I’m using the VSDOC version for the best experience in Visual Studio but you should use the MIN version in production, and consider using the Microsoft CDN

Starting on line 7 I specify a style to be used for the watermark (and names .watermark)

Any texbox that I want to be watermarked I set it’s class=watermark

Note also that the jQuery plugin will use the title attribute as the text to displain in the textbox when the watermark is active as set on line 31.

Then all we have to do is simple apply the JavaScrpt function that begins on line 16.

You can download a runnable sample [ HERE ]


ASP.NET Rounded Coreners AND DropShadow with jQuery.

I’ve started blogging examples of how to replace Microsoft AJAX and the Ajax Control Toolkit usages with jQuery based equivalents.

In this post I showed how to replace the ACT’s Rounded Corner Extender with jQuery and in this one I demonstrated how to replace the Drop Shadow control extender with jQuery.

But lots of folks want to do both at the same time like this.

For this I’m going to use yet another jQuery Plugin – Liquid Canvas.

The code below also demonstrates two different styles of applying the effect. One targets elements with a specific ID and the other targets any element that uses a particular CSS class.



<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs'
		 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <!--[if IE]>
    <SCRIPT type=text/javascript
    src='Styless/excanvas.js'></SCRIPT>
    <![endif]-->
    <script src='Scripts/excanvas.js' type='text/javascript'></script>
    <script src='Scripts/liquid-canvas.js' type='text/javascript'></script>
    <script src='Scripts/liquid-canvas-plugins.js' type='text/javascript'>
	</script>
    <SCRIPT type=text/javascript>
      $(window).load(function() {
          $('#Panel1').liquidCanvas(
            '[shadow fill] => roundedRect{radius:10}');
          $('.rounded').liquidCanvas(
            '[shadow fill] => roundedRect{radius:10}');
      });
    </SCRIPT>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
     ContentPlaceHolderID='MainContent'>
    <h2>Welcome to ASP.NET!</h2>
    <br /><br />
    <asp:Panel ID='Panel1' runat='server' ClientIDMode='Static' 
	                                      style='width: 400px;'>
      <p>&amp;nbsp;&amp;nbsp;&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 4</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 5</a>
		</li>
      </ol>
    </asp:Panel>
    <br /><br />
    <asp:Panel ID='Panel2' runat='server' ClientIDMode='Static' 
	           style='width: 400px;'
               class='rounded'>
      <p>&amp;nbsp;&amp;nbsp;&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 4</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 5</a>
		</li>
      </ol>
    </asp:Panel>
</asp:Content>

The previous posts demonstrate perfectly viable ways to achieve a specific effect, in concert these posts also demonstrate that jQuery has a broad and growing eccosystem and that there are multiple ways to accomplish any given task or effect.

I highly erncourage you to dig deeper into Liquid Canvas as it ofer FAR more functionality than presented in this post.


ASP.NET DropShadow with jQuery.

As I started in this blog post, I’m creating jQuery based samples for all of my origional Ajax and Ajax Control Toolkit guidance. (Find it here.)

In this video I demonstrated adding “DropShadow” visual effects to ASP.NET controls using the DropShadow Control Extender from the ASP.NET Ajax Control Toolkit.

As you might expect, and as you are probably getting used to hearing, “there’s a jQuery Plugin for that”.

You can grab the jQuery “Drop Shadow” plugin HERE.

One of the super powerful things about jQuery is that you can easily select (and apply attributes) via a number of criteria like CSS Class, Element Id, type, etc. For an introductory tutorial on jQuer Selectors read here, for the API documentation read here.

We can add a dropshadow to an ASP.NET container by assigning that container a specific CSS class or ClientId. (Please review ASP.NET 4′s ClientId features HERE.)

It will look like this.

and the code looks like this…..


<%@ Page Title='Home Page' Language='C#' MasterPageFile='~/Site.master'
         AutoEventWireup='true' CodeFile='Default.aspx.cs' 
		 Inherits='_Default' %>
<asp:Content ID='HeaderContent' runat='server' 
             ContentPlaceHolderID='HeadContent'>
    <script src='Scripts/jquery.dropshadow.js' type='text/javascript'>
	</script>
    <script type='text/javascript'>
            $(document).ready(function () {
                $('.rounded').redrawShadow();
                $('#Panel3').redrawShadow();
            });
    </script>
</asp:Content>
<asp:Content ID='BodyContent' runat='server' 
     ContentPlaceHolderID='MainContent'>
    <h2>Welcome to ASP.NET!</h2>
    <br />
    <asp:Panel ID='Panel1' runat='server' ClientIDMode='Static'
               style='background-color:#acc; padding:5px; width: 400px;'>
      <p>&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
      </ol>
    </asp:Panel>
    <br />
    <asp:Panel ID='Panel2' runat='server' ClientIDMode='Static'
         style='background-color:#acc; padding:5px; width: 400px;' 
		 class='rounded'>
      <p>&nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
      </ol>
    </asp:Panel>
    <br />
    <asp:Panel ID='Panel3' runat='server' ClientIDMode='Static'
         style='background-color:#acc; padding:5px; width: 400px;'>
      <p>&amp;nbsp;Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
      </ol>
    </asp:Panel>
    <br />
</asp:Content>

Note the inclusion of the jQuery.dropshadow.js file in line 4.

And then the 2 calls to redrawShadow()


<script src='Scripts/jquery.dropshadow.js' type='text/javascript'>
</script>
<script type='text/javascript'>
		$(document).ready(function () {
			$('.rounded').redrawShadow();
			$('#Panel3').redrawShadow();
		});
</script>

The first call applies a Drop Shadow to any HTML Element who’s class is set to “rounded” and the second applies a Drop Shadow to any element who’s Id is set to “Panel3″.

You can download a working sample HERE.

If you have a specific usage requirement for Drop Shadows, please email me !

Stay tuned.


ASP.NET Rounded Corners with jQuery

Remember the AJAX Control Toolkit ?

I created a LOT of content on how to use it.

While the Ajax Control Toolkit (ACT) is still around, new development on it (by Microsoft) has stopped as we have adopted a more jQuery centric strategy for client UI development.

Not only does this make sense, but I’m compleatly hooked on jQuery so I though I would start demonstrating all the UI things that you could do with the ACT by migrating them to jQuery.

In this video I demonstrated rounding the edges of markup containers in your ASP.NET UI by using the ACT RoundedCorner control extender.

Rounded corners gives our UI a smooth look and there are MANY ways to do this with images, CSS, JavaScript and jQuery.

I’ll use a jQuery plugin to round the corners of an ASP.NET Panel Control.

The final product looks like this.

ASP.NET Rounded Corners with jQuery

I’ve used the jQuery RoundedCorners PlugIn which you can find HERE

It’s TOO simple.

The default ASP.NET WebForms template includes a reference to the jQuery base by default (though you can use jQuery plugins and this code in ANY ASP.NET application.

At the top of my page that will contain rounded corners I add this markup.


    <script src='Scripts/jquery.corners.min.js' type='text/javascript'>
	</script>
    <script type='text/javascript'></script>

When the page is loaded the corners() method is called to apply the rounded corners to all the elements whose class=”rounded”.


    <asp:Panel ID='jQueryBox' runat='server' ClientIDMode='Static'
	     style='background-color:#acc; padding:5px; width: 400px;'
		 class='rounded'>
      <p>Some Developer Links</p>
	  <ol>
	    <li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 1</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 2</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 3</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 4</a>
		</li>
		<li>
		<a href='http://misfitgeek.com' target='_blank'>Developer Link 5</a>
		</li>
      </ol>
    </asp:Panel>

I told you it was TOO easy.

I’ll be doing jQuery alternatives for ALL my Microsoft Ajax and Ajax control toolkit videos.

In the mean time – you can download sample code for the above Rounded Corners demo [HERE].


Podcast-Rey Bango: Scripting, jQuery, Script Junkie, Oh My!

Rey is a scripting dude, member of the jQuery project and management lead on Microsoft’s Script Junkie web site.

In this episode we talk about all of that and the coming wave of new client web development technology.
Resources

Listen

Get Microsoft Silverlight

Subscribe

MP3 WMA M4A Zune iPod

Download

3GP File
3GP
iPod File
iPod
MP4 File
MP4
MP3 File
MP3
M4A File
M4A
M4V File
M4V
PSP File
PSP
WMV File
WMV
ZIP File
Zip
WMA File
WMA
Zune File
Zune

Setting Input Field Focus from JavaScript Code

No matter what flavor of ASP.NET you used (WebForms, MVC, WebMatrix) you probably are (or will be) doing more client side work.  

This is new to many developers, especially ASP.NET WebForms developers who have relied on Server-Side Controls for the majority of their UI rendering.  

As we move more logic to the browser, we require detailed manipulation of the client UI. One of the questions I get is ….. 

How do I put the cursor in a specific textbox ? 

This is useually refered to as setting focus. 

Consider the ASP.NET Page markup below…..  


<%@ Page Language="VB" AutoEventWireup="false"
CodeFile="Default.aspx.vb" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Set Focus</title>

<script type="text/javascript">
onload = function () {
document.getElementById("Text8").focus();
document.getElementById("Text8").value = "Enter Me First.";
document.getElementById("ASPTextBox8").focus();
document.getElementById("ASPTextBox8").value = "Enter Me First.";
    }

function SetMiddleTop() {
var txt = document.getElementById("Text2");
txt.focus();
txt.style.background = "pink";
    }

function ASPSetMiddleTop() {
var txt = document.getElementById("ASPTextBox2");
txt.focus();
txt.style.background = "pink";
    }
</script>
<style type="text/css">
.auto-styletd {
	text-align: center;
}
</style>
</head>
<body>
<div style="text-align: center;">
<br />TextBox Focus with JavaScript<br /><br />
<form id="MainForm" method="post" style="width: 700px; 
                                         margin: 0 auto;" runat="server">
   <table style="width: 100%;">
	 <tr>
        <td class="auto-styletd">
		   <input id="Text1" style="width: 180px" type="text" />
		</td>
        <td class="auto-styletd">
           <input id="Text2" style="width: 180px" type="text" />
        </td>
        <td class="auto-styletd">
           <input id="Text3" style="width: 180px" type="text" />
        </td>
     </tr>
     <tr>
        <td class="auto-styletd">
           <input id="Text4" style="width: 180px" type="text" />
        </td>
        <td class="auto-styletd">
           <input id="Text5" style="width: 180px" type="text" />
        </td>
        <td class="auto-styletd">
           <input id="Text6" style="width: 180px" type="text" />
        </td>
     </tr>
     <tr>
        <td class="auto-styletd">
           <input id="Text7" style="width: 180px" type="text" />
        </td>
        <td class="auto-styletd">
           <input id="Text8" style="width: 180px" type="text" />
        </td>
        <td class="auto-styletd">
           <input id="Text9" style="width: 180px" type="text" />
        </td>
     </tr>
     <tr>
        <td class="auto-styletd">&amp;nbsp;</td>
        <td class="auto-styletd">
           <input name="ClickMe" type="button" value="Click Me" 
		          onclick="SetMiddleTop();" />
        </td>
        <td class="auto-styletd">&amp;nbsp;</td>
	 </tr>
   </table>
   <br /><br />
   <table style="width: 100%;">
     <tr>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox1" runat="server" Width="180px"></asp:TextBox>
</td>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox2" runat="server" Width="180px"></asp:TextBox>
</td>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox3" runat="server" Width="180px"></asp:TextBox>
</td>
	 </tr>
	 <tr>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox4" runat="server" Width="180px"></asp:TextBox>
</td>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox5" runat="server" Width="180px"></asp:TextBox>
</td>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox6" runat="server" Width="180px"></asp:TextBox>
</td>
	 </tr>
	 <tr>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox7" runat="server" Width="180px"></asp:TextBox>
</td>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox8" runat="server" Width="180px"></asp:TextBox>
</td>
<td class="auto-styletd">
<asp:TextBox ID="ASPTextBox9" runat="server" Width="180px"></asp:TextBox>
</td>
	 </tr>
   <tr>
<td class="auto-styletd">&amp;nbsp;</td>
<td class="auto-styletd">
<input name="ASPClickMe" type="button" value="Click Me"
onclick="ASPSetMiddleTop();" />
</td>
<td class="auto-styletd">&amp;nbsp;</td>
   </tr>
  </table>
</form>
</div>
</body>
</html>

  

Note first the onload() function, which is run when the page is loaded in the browser – that begins at line #10.  

Line #11 -  

   document.getElementById("Text8").focus();

 

Puts the cursor in HTML text element whose id is Text8 and the next line adds a bit of text.  

Read the rest of this entry »

Elegant Image Mouse-Overs with jQuery

You can do a lot with CSS but sometimes the usage scenario just calls for the use of an image and changing the image when the user drags the mouse over the image.

I’ve been doing some refactoring on a corporate web site and their navigation menu is mandated to be image based.

You’ve probably seen code like what you see below.

<html xmlns="http://www.w3.org/1999/xhtml" >
   <head>
   <title></title>
   <meta name="Description" content="" />
   <meta name="Keywords" content="" />  
   <script language="javascript" type="text/javascript">
       function mouseOverImage()
       {
           document.getElementById("img1").src = "push-button.jpg";
       }
     
       function mouseOutImage()
       {
           document.getElementById("img1").src = "red-button.jpg";
       }
       </script>  
   </head>
   <body>
   <img id="img1" src="red-button.jpg" alt="image rollover" 
                  onmouseover="mouseOverImage()"  
                  onmouseout="mouseOutImage()" />
   </body>
   </html>
  

It works, but it’s cumbersome and inelegant.

These days, for me, programming in JavaScript is synonymous with jQuery programming.

Here is a jQuery method that I find much more elegant.

 <html xmlns="http://www.w3.org/1999/xhtml" >
   <head>
   <title></title>
   <meta name="Description" content="" />
   <meta name="Keywords" content="" />  
   <script language="JavaScript" type="text/javascript" 
                                 src="jquery-1.4.4.min.js" />
   <script language="JavaScript" type="text/javascript">
   $(function() {
       $('img[data-hover]').hover(function() {
          $(this).attr('tmp', $(this).attr('src')).attr('src', 
                               $(this).attr('data-hover')).attr('data-hover', 
                               $(this).attr('tmp')).removeAttr('tmp');
       }).each(function() {
           $('<img />').attr('src', $(this).attr('data-hover'));
       });;
   });
   </script>
   </head>
   <body>
   <img src="red-button.jpg" data-hover="push-button.jpg" />
   </body>
   </html>
  

With the inclusion of the jQuery library and the little jQuery snippet above, any <img> tag that has a “data-hover” attribute will get the mouse-over behavior.

jQuery just ROCKS !

[ HERE is a working sample. ]

Dynamic Page Menus in WebMatrix Templates with CSS and jQuery.

A basic practice in software development of all types is to use mechanisms that allow us to write and maintain code in a single place no matter how many difference places that code is used throughout our entire application.

When we’re building web sites, and more specifically web pages, the reuse of UI code can be especially challenging as the nature of web applications are stateless and in most models there is a 1-to-1 relationship between endpoints and “files”.

In ASP.NET WebForms we have master pages.

In Microsoft WebMatrix we have Layout Templates.

One of the advantages of the general move towards “standards based” web development is that HTML, CSS, and JavaScript can generally be used across different web development platforms and the technique described below can be used no matter which ASP.NET Development model you choose. (WebForms, ASP.NET MVC, WebMatrix)

I’ll use WebMatrix for the example.

Given a WebMatrix site created using the default “Starter” template the following Home Page and About Page can be displayed when the project is run.

Note that only the text inside the white area of the pages is different in the Default.cshtml and About.cshtml pages.

Read the rest of this entry »

Easy text input limiting with jQuery.

image

I got email from a developer this week having trouble with WebForms validation.

The issue was that a combination of a control and an extender were causing havoc with the counter.

The developer wanted to prevent submission if the user entered more than 50 characters in a textbox.

Note:

  • Using WebForms does not mean you have to do everything with Web Controls.
  • jQuery ROCKS !

When you create an ASP.NET WebForms project using the default template in Visual Studio 2010 you get jQuery included by default.

I did a couple of Bingle searches (like Google only with BING) and found the maxlength.js library at http://www.javascriptkit.com

My .aspx page markup look like this….

Code Snippet
  1. <%@ Page Title=”Home Page” Language=”C#” MasterPageFile=”~/Site.master” AutoEventWireup=”true”
  2.     CodeBehind=”Default.aspx.cs” Inherits=”InputMax._Default” %>
  3.  
  4. <asp:Content ID=”HeaderContent” runat=”server” ContentPlaceHolderID=”HeadContent”>
  5. <script type=”text/javascript” src=”http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js”></script>
  6. <script src=”Scripts/maxlength.js” type=”text/javascript”></script>
  7. </asp:Content>
  8. <asp:Content ID=”BodyContent” runat=”server” ContentPlaceHolderID=”MainContent”>
  9.     <h2>
  10.         Welcome to ASP.NET with jQuery!
  11.     </h2>
  12.  
  13.   <p>Enter some text <strong>(<50 characters)</strong></p>
  14.   <textarea runat=”server” id=”tbonlyfifty” style=”width:300px; height:60px” data-maxsize=”50″ data-output=”in-status” wrap=”virtual”></textarea>
  15.   <br />
  16.   <div id=”in-status”
  17.         style=”width:300px;font-weight:bold;text-align:right; font-size: x-large;”></div><br />
  18.     <asp:Button ID=”ButtonSubmit” runat=”server” Text=”Submit” Width=”300px”
  19.         onclick=”ButtonSubmit_Click” /><br /><br />
  20.     <asp:Label ID=”LabelResult” runat=”server” Text=””></asp:Label>
  21. </asp:Content>

Note how elegant this is.

I simply download and include the maxjength.js file and add two attributes to my html textarea.

data-maxsize – says how many characters can be entered into the textarea.

data-output – tells the maxsize script where to display the feedback.

Note that the textbox is not an ASP.NET Server Side Control. It’s a standard <textarea> element that I’ve specified  runat=”server” and an id so that I can retrieve the value in code-behind.

OR

I could omit  runat=”server”  and retrieve the value from the form collection.

Code Snippet
  1. public partial class _Default : System.Web.UI.Page
  2. {
  3.     protected void Page_Load(object sender, EventArgs e)
  4.     {
  5.         if (IsPostBack)
  6.         {
  7.             LabelResult.Text = “From Request = “ + Request.Form["ctl00$MainContent$tbonlyfifty"] + “<br /><br />”;
  8.         }
  9.     }

Welcome to the power, simplicity, and elegance of jQuery !

For more information on maxlength.js you can go to the source here :

http://www.javascriptkit.com/script/script2/enforceform.shtml 

PS: Here is a working sample [ DOWNLOAD ]

Technorati Tags: ,WebForms,,

Getting ready to move to a jQuery / WCF based AJAX model.

Over the past several years I’ve developed lots of guidance for ASP.NET Developers adding AJAX functionality to their web applications. [ See HERE ]

Most of that guidance has been primarily for Web Forms developers using The Microsoft AJAX Library and the AJAX Control Toolkit.

While those tools are still perfectly viable choices, I’ve added ASP.NET MVC and ASP.NET Web Matrix to the web development work that I do and the above choices are Web Forms centric.

Even in my “Web Forms” applications, I’m using fewer Server Controls in favor of client side User Interface implementations (like jQueryUI and YUI).

Though this is a very different approach than using Server Controls and is usually a bit more coding, it offers the advantages of very detailed control over the aesthetics and behaviors of my browser based UI and it allows me to reuse my client code across Web Forms, ASP.NET MVC, and WebMatrix.

In addition to evolving the client side implementation of my AJAX work, I’m going to be moving from ASMX for services to WCF.

[ Note: I’m going to be doing many videos and tutorials using this model over the coming months. ]

ASMX works fine, but there are many advantages to WCF.

I’ll be blogging specifically about the reasons I’m migrating to WCF in a near future blog post but in the meantime I wanted to introduce you to a CodePlex project that I will be using going forward.

The stiff is being built by the .NET Developer Platform Team so the work here will be reflected in the .NET Stack in the future.

Check them out here – http://wcf.codeplex.com/

Application

WCF Support for jQuery 10.10.27WCF Support for jQuery – create WCF web services that are easy to consume from JavaScript clients, in particular jQuery.

Source Code

WEB HTTP Preview 1.zip – WCF HTTP – create HTTP / REST based web services.

And stay tuned……….

 

Technorati Tags: ,,,

24 JavaScript Best Practices for Beginners

I wanted to share a great article by Jeffery Way over on Nettuts+ on best practices for JavaScript developer.

If your developing web applications, sooner of later JavaScript is inevitable.

I hope you find it useful.

[ Read the article HERE ]

Technorati Tags:

Why would you write your own WYSIWYG editor?

I recently had an email exchange with someone asking me about how to approach writing their own WYSIWYG editor control for web applications.

Perhaps an interesting academic exorcize, or maybe he has some very specific application  but it got me thinking about how many implementations there are out there already !

While searching I found this great list which is lifted entirely from Mike Pope [ Click HERE to Read at Mike's Blog ] – THANKS MIKE !

Rich Editor Controls that you can use with ASP.NET

HTML Editors
As near as I can tell, all of these work in-browser and produce HTML or XHTML.

Word Processing, RTF, PDF, and more
These variously support other formats, notably non-HTML (e.g. RTF) and sometimes PDF.

Other/Not Sure
I’m not sure how exactly these fit into the picture; they’re listed at least in one location as being ASP.NET editors.

  • Community Editor (BigByte). Desktop editing, it says; possibly not in-page HTML editing? Appears to be free.
  • DevEdit NX (Interspire). Not 100% clear that it supports ASP.NET.

More Information

  • A similar list is available at 123aspx.com.
  • Daniel Walzenbach published a list as well in December 2007. With pictures! :-)
  • Scott Mitchell has an article on using FreeTextBox.
  • Building a WYSIWYG HTML Editor” A two-part article by Mitchell Harper. I’m pretty certain that this is for Internet Explorer only, tho.

Scriptloader at SourceForge

 OK you AJAX Masters !

Check out ScriptLoader

ScriptLoader is a framework to manage your and third-part javascript libraries.

It will make you easier to call any script library(your or third-part) without injecting any dirty code.for that,you just configure some info in a configuration file.

http://sourceforge.net/projects/scriptloader/

Intellisense for jQuery

I’m a jQuery Fan !

Lance Fisher has made an update to jQuery for Intellisense in Visual Studio 2008

[ Click here to read about it and download jQuery with the Intellisense updates. ]

Add Custom JavaScript Intellisense

If you reference an ASP.NET page that contains a scriptmanager in your js file like below you get intellisense for the entire Microsoft AJAX Library plus any additional scripts ref’d by the scriptmanager.  The easiest way to get the /// <reference/> entry in your js file is to drag n drop your .aspx page from solution explorer into  the contents of your js file.  VS magically adds the refJ

Since I tend to use stand-alone .js files I can just add this.

/// <reference name=”MicrosoftAjax.debug.js” />

to my consuming page and intellisense is wired to my JavaScript code.

Thanks to Marc Schweigert for the reminder !

JavaScript is Inevitable !

 You’ve heard it. JavaScript is not a REAL programming language.

Well, it is NOW. Programming in JavaScript is inevitable.

And why not.

  • It is ubiquitous. (Supported by all major browsers.)
  • It supports good Object Oriented Development.
  • There is TONS of code out there.
  • There is a rapidly growing collection of rich, high quality JavaScript Frameworks and Libraries available.
  • It’s been good enough to be implemented out of the browser in client technologies like Flash (ActionScript is for all intents and purposes ECMAScript, which is the new name for JavaScript)and SilverLight 1.0)
  • And, Server side technologies like Aptana’s Jaxer

While I concede that “Web 2.0″ technologies like SilverLight 2.0 (Programmed in C#, VB, or any .NET language), and Flash/Flex, and JavaFX have a strong place in the future of the web….. programming the DOM with JavaScript is here to stay.

I think we need to stop trying to avoid JavaScript and start embracing it, even if only for it’s universal availability.

Microsoft is embracing JavaScript

  • We’ve added great development and debugging support fir JavaScript in Visual Studio (see links below.)
  • We’ve developed a GREAT set of JavaScript Extensions that are server independent, free, and open. [More Info Here]
  • Created a JavaScript friendly controls framework. [ See videos #62, #63, and #64 HERE. ]

So, if your ready to take JavaScript beyond the basics, here are some of my favorites to get you started.

Some Books on JavaScript beyond the syntax !

Some JavaScript Tools

Aptana IDE (A GREAT, free AJAX IDE, great for JavaScript even if you’re not doing AJAX)

Antechinus JavaScript Editor

SplineTech JavaScript Debugger

Internet Explorer 8 Beta (With great built in developer tools.)

Some Microsoft JavaScript Links

Microsoft JScript Blog

Microsoft JScript Reference

Video: JavaScript Debugging in Visual Studio 2008

Video: JavaScript Intellisense in Visual Studio 2008

A few better than average JavaScript Web Sites

JavaScript.com

W3 Schools JavaScript Tutorials

JavaScript Kit

Dynamic Drive

DOM Manipulation with JQuery

There seems to be allot of interest with ASP.NET Developers doing DOM manipulation with JQuery there days. I’m finding it a very powerful addition to my client side toolbox so I thought I would share some links that might be of interest.

JQuery Home Page
http://jquery.com/

JQuery Defivition at Wikipedia
http://en.wikipedia.org/wiki/JQuery

Video: Introduction to JQuery
http://aspalliance.com/1495_Video_Introduction_to_JQuery

jQuery Asp.net Controls by David Taylor
http://www.codeplex.com/jqueryaspnetcontrols

Using JQuery to Make Asp.Net Play Nice with Asp.Net
http://blog.spontaneouspublicity.com/2007/08/20/using-jquery-to-make-aspnet-play-nice-with-aspnet/

Using jQuery with ASP.NET MVC
http://www.chadmyers.com/Blog/archive/2007/12/13/using-jquery-with-asp.net-mvc.aspx

ASP.NET and JQuery – first example
http://www.aspcode.net/ASPNET-and-JQuery-first-example.aspx

JQuery and ASP.NET – lets involve ASP.NET
http://www.aspcode.net/JQuery-and-ASPNET-lets-involve-ASPNET.aspx

Visual JQuery
http://visualjquery.com/

JScript IntelliSense: Working with jQuery
http://blogs.msdn.com/webdevtools/archive/2008/02/08/jscript-intellisense-working-with-jquery.aspx

Intellisense for jQuery in Visual Studio 2008

http://brennan.offwhite.net/blog/2008/02/01/intellisense-for-jquery-in-visual-studio-2008/

Microsoft JScript team addressing ECMA deviations.

In their blog, the JScript team at Microsoft is addressing incompatibilities between Microsoft JScript implementation and the ECMA Standard.

From their blog……

“…the first step is knowing where the divergences are. We in the JScript team are looking into where various browser based implementations diverge, where our engine is incorrect in its interpretation of the specification, what if any de facto compatibility conventions have been reached, and the value of codifying such conventions into the standard. We’ve published the first draft of JScript Deviations from ES3 as a starting point.”

Kudos to the JScript team. The haters are quick to slam the IE (and by association the JScript team) for IE’s incompatibilities.

It’s hard to be FIRST, be innovative, and do things exactly the same as everyone else.

Now that the browser “market” has matured and there is more than one browser that matters, I think it’s great that they are taking the heat and addressing the incompatibilities.

Credit where credit is due!

http://blogs.msdn.com/jscript/archive/2007/10/29/ecmascript-3-and-beyond.aspx

Wanna be Microsoft’s face for JavaScript ?

Microsoft makes JScript – our implementation of the ECMA 262 language specification.

Browser script programming is “born again” with the popularity of AJAX and RIA style application building.

So, Microsoft is looking for someone who can represent us and our work with JScript, our support of it, our standards participation, tools support, etc.

You would “champion” JScript to the world much in the way that I champion ASP.NET.

We’re looking for a senior level person with qualifications that include the following:

  • A great working knowledge of web development technologies and especially client side programming in JavaScript/JScript
  • A strong knowledge of developer communities and ideas around how to build one
  • Great presentation skills
  • Rich general solutions development experience.

If your interested, email Shreesh Dubey and convince him that you should interview !

Javascript Debugging with Visual Studio 2008

Kirk has an interesting blog post on debugging Javascript (from a PHP page no less) in Visual Studio 2008 here:

http://blogs.msdn.com/kaevans/archive/2007/08/10/javascript-debugging-in-visual-studio-2008.aspx

Force an UpdatePanel Update from JavaScript

The ASP.NET AJAX UpdatePanel gets updated in one of 3 ways.

1.) An implicit control event triggers an update (that is a control inside the UpdatePanel is getting updated, etc.)

2.) The UpdatePanel has a <Triggers> Collection, and one of the defined triggers gets fired.

3.) The UpdatePanel’s Update metod is explicitly called in the course of some server side logic.

BUT…….  What if I want to explicity trigger an update to the UpdatePanel from my client side JavaScript code ???

Ceck out his link on CodeProject for a solution.

http://www.codeproject.com/useritems/UpdatePanelScriptExtender.asp

JavaScript Encoder

Don’t wanna share your AJAX JavaScript code with any casual browser.

Ceck out this Script Encoder