Basic Element Visibility in jQuery

Out of the box, jQuery comes with basic methods to show and hide elements. There is a live example here of the functions listed in this post.

slideToggle slide the element up/down to hide.show. It handles the toggle state automatically so you don't need to define a separate state boolean.

$("#content").slideToggle("slow");

toggle fades and shrinks the element to the upper left, again toggle state is handled automatically.

$("#content").toggle("slow");

fadeIn and fadeOut perform a fade and collapse/expand the element.

$("#content").fadeIn("slow");
$("#content").fadeOut("slow");

 

In the above examples the parameter "slow" can also be set to "normal", "fast" or a number in milliseconds.

SHARE:

Understanding Lambda Expressions

Of all the additions to the C# language, lambda expressions are potentially the most confusing. Part of this might be due to the odd look of the syntax when you first see it or that a lot of the examples use single letters in the expressions.

The best way to start thinking about lambdas is to think of them simply as anonymous methods.

Suppose we have declared a Timer in a WinForms application as: Timer t = new Timer(); We now need to wire up the Timer's Tick event to some code that is to be executed when the Timer fires.

There are various ways to do this without using lambdas:

  1. Declare an explicit event handler method

    void t_Tick(object sender, EventArgs e)
    {
        textBox1.Text = DateTime.Now.ToString();
    }

    ...
    t.Tick +=new EventHandler(t_Tick); or using delegate inference t.Tick += t_Tick;

  2. Use an anonymous method

    t.Tick += delegate(object sender2, EventArgs e2)
    {
       textBox1.Text = DateTime.Now.ToString();
    };


To write the above using a lambda expression you could write:

t.Tick += (object sender2, EventArgs e2) => textBox1.Text = DateTime.Now.ToString();

Or using type inference:

t.Tick += (sender2, e2) => textBox1.Text = DateTime.Now.ToString(); 

These are examples of expression lambdas. Another type is the statement lambda which is similar but can contain multiple statements enclosed in braces; for example we could write the following:

t.Tick += (object sender2, EventArgs e2) =>
{
    textBox1.Text = DateTime.Now.Minute.ToString();
    textBox2.Text = DateTime.Now.Second.ToString();
};

Note: the => is typically read as "goes to".

Another Example

To print all numbers in a list of ints to a TextBox:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
numbers.ForEach(number => textBox1.Text += number.ToString());

To print all number from 6 and up:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
numbers.ForEach(number =>
{
    if (number > 5)
        textBox1.Text += number;
});

or:

List<int> numbers = new List<int> { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
numbers.FindAll(number => number > 5).ForEach(number => textBox1.Text += number.ToString());

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

Introduction To Extension Methods in C#

Extension methods allow you to extend the functionality of an existing class without using inheritance.

For example, suppose you were implementing a system which allowed users to post comments on a web site but you wanted to disallow swear words or other offensive content.

You could write a SwearChecker class (static or otherwise) or you could enable the same functionality by adding an extension method to the String class.

An extension method is defined a static method within a static class. The keyword this is used before the first method parameter and signifies the type that is being extended.

The following defines an extension method for String.


public static class OffensiveStringExtensions
{

    public static bool IsOffensive(this string stringToCheck)
    {
        // define list of offensive words (real swear words omitted...)
        List<string> offensiveWords = new List<string> {"darn", "damn", "blast"};

        foreach (var offesiveWord in offensiveWords)
        {
            // A real implementation may need to handle uppercase, localisation, etc.
            if (stringToCheck.Contains(offesiveWord))
                return true;
        }

        // no offensive words found
        return false;
    }

}


The extension method is called just as if it were a member of the type itself:

string wordsToCheck = "This is darn offensive!";
if (wordsToCheck.IsOffensive())

    //.... perform some logic ....


MSDN states: "In general, we recommend that you implement extension methods sparingly and only when you have to. Whenever possible, client code that must extend an existing type should do so by creating a new type derived from the existing type."

We cannot inherit from String because it is sealed, so an extension method is one way of adding this functionality to all strings.

Some things to note when using extension methods:

  • If an extension method has the same signature as an instance method, the instance method will be used and the extension method will never be called;
  • The extension method can't access private members of the type it is extending;

If you want to fill in the gaps in your C# knowledge be sure to check out my C# Tips and Traps training course from Pluralsight – get started with a free trial.

SHARE:

A Simple Menu Roll-over using jQuery and CSS

The following ASP.NET page shows a simple example of a menu created using a combination of CSS and jQuery.

The menu is defined as an unordered list (which makes semantic sense) and styled with CSS (a real web site would of course have its CSS defined in external file(s)). When the user moves the mouse over a menu item, a CSS class is dynamically added; then removed when the mouse leaves. In addition a simple "infobox" span is defined whose text is changed to that of the title attribute of the <a> element.

There are lots of examples of image based roll-overs, this one is really cool and based on a simple idea.

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" 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">

    <script type="text/javascript" src="jquery-1.3.2.js"></script>

    <title>Simple jQuery Menu Example</title>

    <script type="text/javascript">

        var menuPrompt = "Please select a page to view."; // simple prompt for user
       
        $(document).ready(function() {

            // initialise the infobox prompt
            $("#infobox").text(menuPrompt);
       
            $(".nav_menu_list li a")
            .mouseover(function() {
                // add the mouseover style
                $(this).addClass("nav_menu_item_mouseover");
                // set the text of the infobox span to the anchor title attribute
                $("#infobox").text("Go to " + $(this).attr("title"));
            })
            .mouseout(function() {
                //remove the mouseover style
            $(this).removeClass("nav_menu_item_mouseover");
                // reset the text of the infobox span to user prompt
                $("#infobox").text(menuPrompt);
            })
        })
   
    </script>

    <style type="text/css">
        .nav_menu_list
        {
            list-style-type: none;
            margin: 0 0 0 21px;
            padding: 0;
        }
        .nav_menu_list li
        {
            float: left;
            text-align: left;
        }
        .nav_menu_list li a
        {
            display: block;
            padding: 0 10px 0 5px;
            text-decoration: none;
            font-size: 36pt;
        }
        .nav_menu_item_notmouseover
        {
            color: #0000FF;
            background-color: White;
        }
        .nav_menu_item_mouseover
        {
            color: White;
            background-color: #ec1c24;
        }
    </style>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <ul class="nav_menu_list">
            <li><a title="Page 1" href="#" class="nav_menu_item_notmouseover">Page 1</a> </li>
            <li><a title="Page 2" href="#" class="nav_menu_item_notmouseover">Page 2</a> </li>
            <li><a title="Page 3" href="#" class="nav_menu_item_notmouseover">Page 3</a> </li>
        </ul>
        <div style="clear: both;">
            <span id="infobox"></span>
        </div>
    </div>
    </form>
</body>
</html> 

SHARE:

Changing background image on <body> element with jQuery when using ASP.NET master pages

If you have an ASP.NET master page defined as below which specifies a css class for the body element to generate a background image for the whole page, you might want to override the default background on specific pages.

One way to accomplish this is to use jQuery to replace the css class that is being applied to the <body> element.

The master page below declares 2 ContentPlaceHolder controls; the first (ID="head") exisist within the <head> element, the second (ID="MainContentPlaceHolder") exists within the main body of the page.


<%@ Master Language="C#" AutoEventWireup="true" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>
<!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">
   
    <script type="text/javascript" src="jquery-1.3.2.js" ></script>
   
    <asp:ContentPlaceHolder ID="head" runat="server">
    </asp:ContentPlaceHolder>
   
</head>

<body class="defaultbodybackground">
    <form id="form1" runat="server">  
        <asp:ContentPlaceHolder ID="MainContentPlaceHolder" runat="server" />
    </form>
</body>

</html>

 

 
In one of our child pages we could add the following:


<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
 
    <script type="text/javascript">

           $(document).ready(function() {
               $("body").removeClass("defaultbodybackground");
               $("body").addClass("newbodybackground");
           })
        
        </script>
</asp:Content>


When the page is loaded, the above jQuery JavaScript runs and replaces the class "defaultbodybackground" with the page specific "newbodybackground".

A cool thing about jQuery is that you can have multiple $(document).ready() defined - for example you could also have some jQuery defined in the master page.

SHARE:

Throttle Your ASP.NET Connection Speed

As a tool to test responsiveness on slow connections Firefox Throttle is handy Firefox add-in. There is also an IE version. You can add a localhost throttle if you are using Visual Studios local web server. For example, setting the download speed to 56K dialup, you can check any Silverlight media buffering UI animations are working as expected.

SHARE:

Determine site’s absolute, fully-qualified url in asp.net

 I'm working on a Silverlight media player like you get on MySpace and other sites. The app is meant to be as simple as possible, so i've created a Silverlight-enabled WCF service which returns a list of the MP3s available in the songs directory on the server. To allow the SL app to be as loosely coupled to the location of the physical mp3s, the wcf service needs to return a list of fully qualified URIs to each mp3 in the directory. When the user selects a song to listen to we can simply set the MediaElement.Source to the URI.

 The following post contains some great code (that can even be used outside of a WebForm) to convert  "~/myfolder/mysubfolder" to http://foo.bar/myfolder/mysubfolder".

http://stackoverflow.com/questions/121962/determine-sites-absolute-fully-qualified-url-in-asp-net

 

SHARE:

Microsoft Certified Master Program

The 3 week master program costs US$18,500 (I'm assuming not inclusive of accommodation!) and runs in Redmond, Washington.

You have to be accepted onto the program by supplying a CV and potentially a 30-60 min interview (after paying $125 non-refundable fee).

 http://www.microsoft.com/learning/mcp/master/register/default.mspx 

SHARE: