Invert the Transparency in an Image with Gimp

You can easily invert the transparent parts of an image with Gimp. Gimp is an open source Photoshop alternative.

Follow these steps:
  1. Choose Colors -> Components -> Decompose from the menu and set Color model to RGBA.
  2. A new image is opened with all color channels (including alpha channel) decomposed as single layers.
  3. Select the layer alpha and choose Colors -> Invert from the menu.
  4. Choose Colors -> Components -> Compose from the menu, set Color model to RGBA and make sure the layers are correctly mapped to the channels (should default correctly if you did not reorder the layers)

It will open a few new Gimp tabs but it will, indeed, invert the transparent areas of the image. This worked well for me on an image of a single color with transparency.

Read More

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 with JavaScript Closures.

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. This is also known as a JavaScript Closure where functions have access to private variables that nothing else can touch or modify.

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

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

Self-Closing Bootstrap Modal in MVC

I had a need recently to alert users if the amount of records being selected differed from what they expected. My notice was more of a "heads up" then anything. Still, I wanted to give users a way to abort situations where job size would pose a threat or hinder productivity. I also wanted to avoid extra interface clicks, especially in situations where they typically accept. That’s when I came up with the idea of a self-closing dialog. The user would be presented a modal message informing them of the difference. To proceed they could press the Continue Immediately button, close the dialog (via the title bar), or step away and wait for the timer to run out. The process only aborts if they they click the Cancel button in the allotted time.

This project could be done in a multitude of ways. Being an MVC fan I opted for that route. I decided to utilize partial views as well. Regardless of your approach you will likely need to contact the server to crunch your numbers and detect the differences. To do this you will probably use ajax:
On the backend we receive our data using a controller and models:
Next, comes the partial view. Notice I’m declaring a model and using it to retrieve values:
I also have some script in the partial to drive the modal:
And there you go.
  1. We click a button that fires ajax
  2. The ajax talks to the server
  3. The server detects differences
  4. The server populates a model then generates a partial view
  5. The partial view is returned to the ajax callback function
  6. The callback function adds it to the DOM and executes the script

Like I said this could be done in a dozen different ways. You could have the modal hidden on the parent, use ajax to fetch the figures themselves, then modify the modal before making it visible (see DEMO below). You could also use webforms to do this and use ASP.NET web server controllers instead of partial views.

See a DEMO.

Thanks.

Read More