Better Image Previews in HTML5

When working with an uploader it’s nice to show image previews of files before the actual upload takes place. It looks nice and verifies to the user that the correct files have been selected from their computer. Since they are local files people expect them to render immediately. This article details how I accomplished this in HTML5 without the use of flash, silverlight or any other dependent technology.

Over the last several weeks I’ve been researching Plupload for image uploads. They have a nice, ready-made widget but it didn’t quite capture the look and feel that was requested of me. I opted to rely on their API and do the interfacing myself, which included developing my own image previews.

My main requirement was for them to render quick, even with 20MB files. My project was tailored to professional photographers so big files were expected. Searching the web I tried a few techniques that seemed to perform well with small files but would max out resources for larger ones. Things became choppy. A page quickly looks cheap when buttons don’t respond to clicks, content freezes intermediately, etc. I had to come up with a different solution. Along with speed, I also wanted to keep consistent thumbnail sizes and perform ideal cropping. Image quality had to be fair and recognizable as well.

The first function handles proportional resizing. I needed to be able to retrieve lower dimensions that didn’t skew or distort an image:
In most cases you’ll end up with one property that meets the max, but the other dimension will be much smaller than its max. For thumbnails to look clean you need a consistent width and height for every image. So that means you will likely need to crop. But you don’t necessarily want to perform that action on the entire image. Everything becomes so small it becomes hard to read. Rather grab a portion of the image as your scaling down. The following function utilizes proportionalResize as it determines the best coordinates for presenting your image:
Finally, we get to the meat of the process. This function returns the preview as a <canvas> element for your page. A <canvas> tag resembles an <img> tag with one big difference. Instead of loading the image from the network it’s drawn via JavaScript. It also has a built-in cropping mechanism. If using Plupload pass the result of file.getNative(). If not refer to this resource for getting a FileList of File objects to be passed in individually. This function calls the aforementioned centerCropFit function:
Originally, I tried Filereader.readAsDataURL() which converts the entire file into base64-encoded string. Whenever I assigned it to the src of an image it would cause a big memory hit for large files. Attempts to use window.setTimeout() to get around the heavy processing did not help. I also explored Web Workers to no avail. The URL.createObjectURL() method is the nitrous behind this process and allowed the tool to perform well for the user.

Read More

Ensuring Variable Integrity in Async Callback Functions

Callback functions to asynchronous requests may need to reference variables outside of itself. This can be problematic because those variables might not maintain the values you expect by the time the callback function fires. In the past I’ve dealt with this by writing my code as a string, concatenating my variable values, then using eval on it in the callback. I never liked this technique because it seemed amateur, risky and unreliable for complex scenarios. Recently I came across a clever solution that seems to work quite well:
Here we wrap a function around the code, and execute it immediately passing the target variables into it. In my example the variables are file and uploader. Next, we then have an inner function that keeps the meat of our code from being executed immediately. It will be executed in the callback of the asynchronous process…but can reference the variables passed to it’s wrapper function. In the example I have used the same variable names again (no need to change them). I believe the technique duplicates the variables into a local scope where its values can be maintained.

Here is a FIDDLE showcasing the technique. Enjoy.

Read More

Creating Animated Spinners with FontAwesome or Glyphicons

When creating JavaScript-rich applications an indicator is often used to give the user some certainty the page is working behind the scenes. If not present a user may question if the page has stalled or not. An animated GIF known as a spinner (or loader) is a common way to achieve this. An alternative to linking to a specific image is to use a popular font library that you may already be referencing by your application.

FontAwesome

The ability to create spinning icons in built into FontAwesome. Reference the library and create loaders easily:
The fa-spin class is what causes the rotation.

If you desire a different animation speed then you need a little CSS:
FYI: this CSS was constructed by studying the fa-spin class found in the FontAwesome stylesheet. Adjust the milliseconds (i.e., 1000ms) to alter the speed. Higher is slower, lower is faster. The default speed used by FontAwesome is 2000ms.

To use simply replace the fa-spin class with fa-spin-custom class that you have made:

Glyphicons

To use the font-library built into Bootstrap you will need to reference the above CSS as well:

That’s it. See a DEMO.
Enjoy.

Read More

Distinguish Between Posts & Pages in WordPress

Have you ever had a need to distinguish between pages and posts? At one time I had a request to show ads on all posts but to exclude pages. I’m sure if I dug deep enough I could find a plugin to do handle the cases, but it’s really not that hard to distinguish between the two.

If you prefer to do the checks in php you can reference some built in functions:
If you would rather use script then the following is what you need:

Read More

DataTable Fundamentals Part 2

Continuing from Part 1 of my study on the fundamentals of jQuery DataTables I wanted to discuss a few more topics. In these examples I’ll refer to the following DataTable object using DataTables version 1.10.0+:

Settings

At some point you may wish to retrieve your DataTable settings in a certain scenario or event. This can be done a couple different ways:
Simply loop through these setting objects to retrieve all properties and values

Custom Settings

The above methods will work fine to retrieve any official settings. But what if you want to set a custom setting that makes since only for your project? To get to the value of a custom attribute you must drill deeper into the settings object by viewing the oInit property:

Re-Retrieve DataTable Object

Depending on your scenario you may have lost or do not have access to the original DataTable object. You can re-retrieve it without interfering with the table:
Alternatively, if you don’t know the TABLE id either you can refer to a global variable. Then you can loop through them and re-retrieve the object like we did above:

Removing DataTables

Any good plugin that manipulates the DOM should have a way to remove all transformations and events it has made without removing the element itself. DataTables has this built in:
Note: I’ve also had success with jQuery’s $.empty function to remove all data and event handlers when called on the DataTable’s parent.

Search on Enter

One of my annoyances is how DataTables will search on every keystroke. This is great if you are dealing with local data but if you are relying on ajax requests for data then this can be a lot of strain on the server. To override this functionality do this:
Note: Bootstrap 3.0 seems to remove the clear button in the filter textbox

Read More

Floating Element that Scrolls with a Page

I occasionally have a need to show a note or message to a user that must remain in vision. When the page is scrolled vertically the message moves with the content. I usually want the message in the center of the window, to the right of my content. The movement must be fluid and responsive, not choppy like back in the early days. This can be accomplished with little effort:

We must add the markup that will be moved around. Of course, you can expand upon this however you see fit:
Now, with some CSS we style the element and set it’s position:
This will position the element at the middle, far-right of the page. Of course, this may look a little spaced-out if you have a high resolution. This bit of script will snug it up next to whatever element you wish:
This code does some adjustment based on resolution. It compares the browser’s viewport width to the space required to show your message next to the target element. If it exceeds then the message will just ride the right of your page, hovering any content it passes while scrolling. If it fits then it will be nestled next to it.

See a DEMO.

Thanks.

Read More

Convert Razor Validation Summary into Bootstrap Alert

In MVC, if you use the Validation Summary method any validation errors for the model are presented back to the user in a bulleted list. If you have been using bootstrap throughout the site you may want to give this message the same look and feel to have consistent interfacing. This error summary can easily be converted into a bootstrap alert to show to the user. Simply expand upon that call with this logic:

By default, @Html.ValidationSummary() returns nothing if no errors. But since we are adding additional markup for the bootstrap alert we must check for errors ourselves. The result will be a closable, danger alert with a heading and bulleted, error list inside.

Next, you may want to clean up the classes added by the validation summary. This can ensure that you will not have any CSS rendering issues as well as expanding upon the bootstrap look. I simply added this javascript at the bottom of my view:
The first call cleans up the list itself. The second call will put a bootstrap danger highlight around your fields with the issues. If the red outline does not appear then make sure you are following bootstraps recommendation of wrapping form elements and their labels in a form-group class. For example:

Read More

WPF Label – Click and Focus on Element

WPF applications have labels and controls but, unfortunately, they don’t integrate together as easily as in HTML. In HTML you rely on the id and for attributes to bind them together. Then when the label is clicked the control gets focus. So in that environment labels serve to identify the control, as well as aid in accessing it. Sometimes it’s easier to click on a label then the form element itself, such as with checkboxes and radios.

I wanted to achieve the same effect in WPF. I accomplished this by creating and referencing my own customized label. The new label inherits all the features of a traditional label but also includes a few others.

To begin, we create the class. Out of the box a WPF label will stretch horizontally to fill the entire area it resides in. By setting the HorizontalAlignment it collapses it down to the width of its content. This can be overridden in the xaml. We then give the element focus based on a mousedown event.

I also have a bit of code just for textboxes. Once focused the cursor will be placed at the front of any text. You can use the code below to move the cursor to the end, or select the text.
Next, we need to reference the new label in the xaml. To do this we must declare a namespace in the Window object then reference it on each call to the control. The example shows EnvelopePrinting. Replace that with the name of your namespace. We also use Target attribute and Binding call to link the two elements together.

Read More

Self-Closing Bootstrap Alert

Alerts are a nice feature in Bootstrap to grab a user’s attention and deliver information. The different types of alerts are success, info, warning and danger, which are color coded accordingly. Alerts can include a close button for users to remove it from view once they have read it. In my project I wanted success alerts to show to users then, after a few seconds close on their own. This can be done easily with jQuery’s fadeTo() function. You can also incorporate a slick transition effect with the slideUp() function.

Create a success alert via bootstrap
Then you just need a little script. This script targets only success alerts and will close it after 5 seconds:
See a DEMO.

Read More

Using ASPX Like MVC

I love the organization of MVC when it comes to delivering content. Using a server-side controller you can see all the routing activity of your program. The controller can interact with the parent view as well as related partials, passing data and rendering html. Related views are also tucked-away together in the tree making it easy to pinpoint what you’re looking for. The default layout of WebForms is a different kind of animal. But using MVC experience as a reference you can structure your project to work in a similar way.

To begin we want to create a Views folder and inside that create a Home directory. The Home directory will contain the parent ASPX as well as any child ASPX pages for the dynamic content. When naming the child ASPX files be sure to prefix them with an underscore to follow MVC convention:

Tree Example

Next, we need to refine the Site.Master (or _Layout.cshtml in MVC). Make sure to add the script and style bundles to get jQuery and Twitter Bootstrap on the page. The ContentPlaceHolders (or sections in MVC) allow us to have placement control:
If any bundles are missing they can be added in App_Start/BundleConfig.cs.

In this example the parent ASPX contains a button that performs an ajax request. ContentPlaceHolders are used to inject code snippets in the proper location within Site.Master:
This is pretty straightforward. The script performs an ajax request to a partial ASPX. It passes data and retrieves HTML that is displayed to the user. The Index.cs file is not touched.

Next, we want to ensure the server can locate our parent page. A simple adjustment to the Web.config can accomplish that:
Now on to Models. You can also create Models to share between parents and partials. When creating a new Web Forms templated project it comes with a Models folder already. Inside is a model for account identity. Create a HomeModel.cs and place it in that folder. Next, add the following model to it which will be referenced later:
In any ASPX file you can add a using statement to reference our models:
Replace WebForms_Ajax with the name of your project. After that, all models can be shared between ASPX pages. This can reduce redundant coding.

The last step of the process is the partial. Under /Views/Home create an ASPX page named _Incomplete.aspx. The UI looks like:
Notice we have a full HTML document here. This is necessary to use the ASP.NET Web Server Controls. If you don’t include surrounding <html> tags then it won’t recognize tags prefixed with asp. But don’t worry, when we return the markup via ajax it won’t have any of that. We simply grab the contents of the <asp:PlaceHolder> tag.

Take note of the tags. This is what we use to add data to our page. They will repeat one to many times to add content to the page. Inside that repeater is another repeater whose data source is set automatically. The Eval() calls relate to the property names of our model.

The code behind does the magic. In Page_Load we fetch the data that was passed. It can be used to retrieve any additional information from a data source. Next, we construct our model to pass to the page. The model was declared in HomeModel.cs The RootRepeater is the name of the outermost repeater. We set the class equal to it’s data source. Notice we are placing the model in a list. A repeater requires a list or other IEnumerable object to work. Lastly, we grab the contents of the placeholder and return it with the response:
Download a DEMO.

Read More