Archive | JQuery RSS for this section

Angular Auto Form Validation Summary

One of the more mundane things in Angular is creating validation messages. If you come from .Net you’ll probably be screaming as your views have always just pumped out the validation based on Data Annotations from your class models/view models.

Well we’re one in the same because I hate writing the same thing over and over again. This is a quick directive I built to iterate over a collection and build out those little guys for me. It has a the ability to show a summary or display errors below the associated control. There are a few other options that affect behavior as to when the messages trigger or show.

See the Github page for installation and use instructions.

angular-validation-summary

Build AngularJs on Windows

Clone Repository

First clone the git repository for AngularJs. If you don’t already have git or are unfamiliar with git you can download and install Git for Windows. This is likely the best option for you if you are relatively new to git. You’ll be able to click the “Clone in Windows” button on the right of the AngularJs repository.

Install Development Dependencies

If you don’t already have the NPM package manager installer on your machine you’ll need to install it. Probably the easiest way for you is to install NodeJs. This will install the package manager which is very handy, for much more than this task. Choose the option for your platform here.

Once you have NPM installed you can now finish setting up the dev utilities that you’ll need. AngularJs among many other frameworks and apps build via Grunt. You’ll also need Bower. To install both along with a few other dependencies just run the following from the directory you’ve cloned Angular to:

npm install

Once you have run npm install you’ll need to install the grunt-cli and bower but we’ll need this installed globally. To do so add the -g flag as such:

npm install grunt-cli -g
npm install bower -g

The Missing Environment Setup

There are a few other things that you might get stuck on when trying to build AngularJs via Windows. You’ll need the Java Runtime Environment package installed. This is used quite often and you may already have it installed. If not go here grab it and run the installer for your platform.

Once you have java installed you’ll need to add some Environment Variables to make the build happy. In order to do this click your start button for right click “Computer” from Explorer and choose properties. Next choose “Advanced System Settings” on the left of the window. The advanced tab will open and you’ll see the “Environment Variables” button on the bottom of the dialog window.

You should now be in the Environment Variables dialog on the top you’ll see user variables and the bottom system variables. We’ll need to modify both.

Add Java to Path

Double click on the line that says “PATH” or highlight and then select edit. Go to the end of the line and add a semi-colon. After the semi-colon add the path to your java runtime environment. Probably something like C:\Program Files (x86)\Java\jre7\bin if you are on a 64bit machine. Add that to the end of the line and then select OK.

JRE Variable Path to Bin

Setup Java Virtual Machine

In the System Variables you’ll need to click “New” and add a new key value pair. For the variable name use _JAVA_OPTIONS and for the value use -Xmx512m. This will setup the basic options you’ll need for the virtual machine. Say OK and close out of the dialog boxes.

Java VM Options

NOTE: Be sure to close out of any command prompt windows you might have had open. If you started to run the build process before completing the above it won’t work so after installing make sure you’ve closed out of your command windows and then re-launch.

Running the Build

To actually package up the library is a snap you need only run the grunt command which will call the pre-configured Gruntfile.js for you and package it all up into the “build” folder in your repository directory. The command is below:

grunt package

Now What

Get involved and contributed to this awesome project. How do you do that? You can find it all => here.

Smart Table for AngularJs Extended

What is Smart Table

Smart table is module and set of directives to assist in sorting and paging a table/grid of data. I liked it as it doesn’t try to do too much and is simplistic to extend. No offense to some of the other grids but many I found tried to do too much and that usually spells disaster. Why? Well, there’s always something you need that due to the design you have difficulty doing. Smart Table handles the basic functions and leaves it at that.

So here is an extended version that adds a couple nice features that make it have more of the Datatables Bootstrap feel. This is optimized for Bootstrap 3 but with little work you should be able to adapt it to your styling needs.

The zip contains the illustrator file used to create the sort icons, the compiled .css file, the Smart Table debug source and a less file for those that are importing Bootstrap and compiling .less. if you don’t know what LESS is don’t use that file.

You’ll also notice is the source file you’ll see /* START MODIFICATION */ anywhere the source has been modified. Hope it helps Email in source if you have ques.

Disclaimer: Just started playing with Smart Table literally today so if you can improve upon the code please do so and comment/email. Perhaps the author can take a look as this was a very quick fix for my needs.

Screenshot

Smart Table

Smart Table

Download

Download the files here from Google Drive

Zepto.js Rakefile

This is a Rakefile to substitute the default in the Zepto.js mobile framework.

Note the extension on the download file is .doc. This is because WordPress limits the file types that can uploaded. Be sure to rename it with no extension.

Download Rakefile Here

Zepto.js Home Page

Zepto Source on GitHub

Kendo UI MVC Grid Extention

Kendo UI MVC Grid Extention

Didn’t like how the MVC Destroy() method worked so I wired up my own. This is a simple function to help you get the row’s data when you fire off the custom event.

Essential “e” is the event that is fired from the custom command event in your Kendo UI grid. It takes the target and turns it into a JQuery object. It grabs the uid of the row and then matches it with the uid in the data. Its very quick and works nicely. Sure there are other ways to skin this cat but this seemed to be very smooth. Seems to me there should be a JQuery data object for the row but all I saw was the uid hence this function below. Anyway thought I’d share.

   function getRowData(e) {
        var target, grid, uid, row, data;
        target = $(e.target);
        uid = target.parent().parent().data().uid;      
        grid = $('#Grid').data('kendoGrid');        
        row = grid._data;
        for (var i = 0; i < row.length; i++) {
            if (row[i].uid == uid) {
                data = row[i];
            }
        }
        return data;
    }

What you’ll get is your data for the row as an object so you can simple do:
// note below assumes you have a custom column command that on .click() is attached to the “deleteRow” function “e” is the event that the click event will pass in.

function deleteRow(e){
	var data = getRowData(e);
	var name = data.full_name // where full_name is a column in your grid. 
	alert('Are you sure you want to delete ' + name);
	// TODO: wire up your delete event passing in an id or something
	$.post('/your/path', {}, function (result) {
		if(result.deleted){
			// load your UI or whatever
		}
	});
} 

The getRowData function you can copy/paste but the above “deleteRow” is just an example you’ll need to modify to your needs.

KnockoutJs and Ifragistics JQuery IgGrid

The Problem

Ran into a problem with the extensions shipped from Infragistics for use with the IgGrid and KnockoutJs. JQuery kept breaking complaining about “object not a function”.

After doing some digging and messing around I realized there was a problem with the shipped extension. I noticed a demo on Infragistics site that referred to a CDN version. So I grabbed it and it worked just fine. No more “object not a function” errors in my console using Google Chrome. So if anyone else runs into this issue just grab the download below and overwrite the shipped file and all should be well.

Knockout and the support from Infragistics is relatively new so I’m sure there will be updates in the meantime this works. as of the date of this article. If you are checking this a month or two from now they’ve probably resolved the problem.

Download Update

infragistics.ui.grid.knockout-extensions.js

Blurred Coupon Code using JQuery

Securing a Coupon Code

Got asked to create a way to blur out a coupon code until a link is clicked today. Stop now if you’re looking for some eye popping, earth shattering effect because it’s not here..LOL. However it is kind of cool to see how it works, or at least one way you can do it.

The Concept

Blurred out Coupon Code

First let me say that I think if you really want to secure it up you may want to make a quick ajax call or something. Essentially never having the coupon code touch the DOM until you need it. That might be overkill and since I was adding this as kind of a widget for someone, not having direct access to the site, this worked well.

Secured Until Clicked Coupon Code

First thing I did was create a couple buttons. Nothing special they could even be just a link. The next they I did is create an image that had a code then I blurred the text using Photoshop. So basically our blurred out or secured code is the same each time but to the user it just looks like an unreadable code. So here we go. Let’s start with just a touch of css.


.blur { background-image: url('your_fake_blurred_coupon_code.jpg'); }

I’m assuming you understand what JQuery is and how to add a reference to the library either local or CDN. Now that we have that out of the way lets look at some markup. Below we have an anchor wrapped around an image. Again you could do without the image if you wanted. Take note of the two classes here that we’ll be using with our JQuery. That being “getcode” and “code”

Secure/Blurred Html Markup

Next lets look at the actual JQuery. When the page is ready JQuery iterates of “.code” essentially storing the actual coupon code in the element’s data cache. Hence preventing the typical user from just viewing source. Mind you this isn’t locked down as I mentioned. As the page loads if you were to look at the raw data you’d see these codes before JQuery iterates over them but we’re not trying to thwart that caliber of user. We’re trying to make sure Joe blow click the link so we get paid. So JQuery stores each code in data cache then makes the element’s text empty. These examples are more verbose than what I actually used, but should help be clear what’s actually happening.

When an element is clicked it retrieves the data from cache shows the coupon by appending a new element that fades in with our original code. and then opens the link to wherever its going with an assumed query param or something that the third party sees.


$(document).ready(function () {

$(‘.code’).each(function () {
var code = $(this).text();
$(this).data({ secure: true, code: code });
$(this).text(”);
$(this).addClass(‘blur’);
});

$(‘.getcode’).click(function (e) {

e.preventDefault();
var hasCode, url, code, data, showCode;
hasCode = false;
showCode = $(‘

‘);

url = $(this).attr(‘href’);

if ($(this).next(‘div.code’).length > 0) {
hasCode = true;
code = $(this).next(‘div.code’);
data = code.data();
}

if (hasCode) {

showCode.text(data.code);
code.append(showCode);
code.removeClass(‘blur’);
showCode.fadeIn(800);

// change window open settings to whatever you prefer
window.open(url, ‘Get Coupon’, ‘width=600, height=400, top=200, left=300’);
}
});
});

Wrap Up

Not rocket science but that’s one way you can do it. Below is the faked blurred out coupon code graphic.

Blurred coupon code mask.

Jquery Live Image Crop

Live Image Cropping

I’m sure by now you’ve seen similar tools. Nonetheless I wanted to post this demo for those that haven’t. This demo leverages Jcrop. I won’t get into the details here as their documentation is self explanatory. What I will do is cover what you can do with it after you crop the image. That is where some of the real magic shows up. Cropping itself is rather simplistic. Demo Here

Crop demo screenshot

Live JCrop Demo

Init JCrop


function initJcrop()//{{{
{
// where target is the target image.
$('#target').Jcrop({
onRelease: releaseCheck, // checks for release
onChange: getCoords, // gets the coords and updates the inputs.
onSelect: getCoords // same as above just a different callback.
}, function () {

jcrop_api = this;
jcrop_api.animateTo([259, 81, 469, 304]); // create the corp box at these coords (x, y, x2, y2)

// Set the default checkboxes
$('#resizeable').attr('checked', 'checked'); // whether or not you can resize crop.
$('#aspect').attr('checked', false); // should it be forced to a specific ratio.

});
};

Force Aspect Ratio example trigger using JQuery on checkbox

This is just one example but setting up these options are all very similar


$('#aspect').change(function (e) {
jcrop_api.setOptions(this.checked ?
{ aspectRatio: 4 / 3} : { aspectRatio: 0 });
jcrop_api.focus();
});

Saving the Crop

Here were are making a simple post passing a Json representation of the coords, then await response from server.


$.post(postPath, jData, function (result) {
if (result.saved) {
// here I'm check if in the json result if "saved" is true.
// if yes DO SOMETHING...
} else {
// if not show an error of some sort.
}
});

In the demo after the crop is saved, I simply update the path to the image, the newly cropped image that is.
You’ll notice a “view crop” button that shows it. This is all just for example. Normally when the dialog opens that you’ll see
you might have an input for new filename or perhaps save location or other criteria you want saved to your database. In
fact you don’t need the dialog at all but since this is a static representation/demo I needed somewhere to display the result
and didn’t want to leave the page.

Saving to File System

Unfortunately this is beyond the scope of this article. Mainly because I have no idea what platform you’re one so its pretty tough to give an example. What I can tell you is
that its actually rather trivial for the most part. For example in C# you might do something like this:


var img = Image.FromFile(imgPath, true); // get the image you were working on from file, you could also do this from stream.
Image newImg = new Bitmap(img); // now we have a new image to work with.

var netImage = NetImage.Crop(newImg, w, h, x, y); // here we are taking the coords from JCrop passed in our Json and cropping the image.
// note the above is a custom class that crops images in various ways.
// above result from our custom class is a System.Drawing.Image. we can now save it or do what we wish.

If you’re using say NodeJs(which is amazing stuff btw) or Rails you can investigate Node-Canvas or perhaps ImageMagick.

Conclusion

It really is rather simplistic to crop images. It really is up to you and your design how you want to go about it. What options or restrictions you want. Perhaps you’re wanting to keep each image cropped to a specific ratio or size. Live for profile photos that should only be say 100 x 100. All very easily obtainable.

This is not meant to be a complete start to finish tut. It is meant to point you in the right direction. You can also expand the source on the demo. As always you can send comments and questions and I’ll help if able. You can also hire us for your next project!

Jquery Tagit Extended

Took a few moments today and extended a popular plugin a bit. Use at your own risk as I haven’t tested this to the fullest however it seems to be fine. The modifications were minor as well.

About the Extension

Throughout the source you’ll notice the comments [MODIFICATION] that indicate where the source as been extended. You’ll also notice [END MODIFICATION] to let you know where the original authors source begins again. If you’d like to checkout the original author’s site please do so here. You can obtain my source with the below added features and extensions by DOWNLOAD. Note this is just the .js file and does not include the entire source with stylesheets. Please download this from the author’s site.

Features Added

    minTags – This will make sure no less than the number indicated can be removed. Default is 0.
    maxTags – No more than this many tags can be added. Default is 0 which is unlimited.
    requiredTags – This is an array of strings that must exist and cannot be removed if present. Perhaps a user group or something where there must be a default. Default is null.
    restrictToAvailable – Default is false. If enabled. Only tags in the “availableTags” object can be added.
    onTagRemoveFailed – When a tag cannot be removed due to one of the above constraints this callback is fired. Default null.
    onTagCreateFailed – This is called when a tag cannot be created due to a constraint. Default is null. Use this to give feedback to user if you will.

How to Use

I would encourage you to visit the author’s site for full details and instructions but this will get you going. The below assumes you have referenced the “jquery-tagit-mod.js” file in the header of your page and that you have referenced its companion css stylesheet as well.

$(document).ready(function () {
$('#mytags').tagit({
availableTags: ['tag1', 'tag2', 'tag3'],
onTagRemoveFailed: function (event, tag) { console.log(tag.children('span.tagit-label').text() + ' cannot be removed.'); }
});
});

JQuery Horizontal Bar Chart Plugin

This is a very simple bar chart plugin using unordered lists and divs. You can populated the data either statically using data-dash attributes for the

  • items or you can add it inline in the data: option of the plugin. If you use the data-dash attributes the plugin assumes that it takes priority and overrides the data: option of the plugin. The plugin allows you to easily change css styles for the auto generated
  • ,
    and elements it creates. This is a very simple plugin with a handful of options. If you are looking for something really comprehensive this probably isn’t it. The purpose of this plugin is to quickly make a simple bar graph that shows a percentage based on some calculation. Essentially the value you supply for the bar is calculated against the size of the bar (either specified or auto generated based on element width). Obviously this could be extended quite a bit and rather easily so have at it. The reason I created this plugin is that the majority of the chart type plugins out there are far more complicated than I needed for this simple task. Hence the focus was to keep it as simple as possible while providing a handful of anticipated options for reuse in projects. The plugin does provide the ability to callback.

    Download: DOWNLOAD

    Below is an example of what it might look like.
    Quickbar Example

    First add some css. Again you can change the css style names to your liking in the plugin.


    .quickbar { padding: 0px; margin: 0px; list-style: none; } /* this is the actual ul */
    .quickbar li { padding: 5px 0px 5px 0px;}
    .quickbar-container { background-color: #F3F3F3; display: block; line-height: 20px; overflow: hidden; border: 1px solid #EAEAEA;
    border-radius: 3px 3px 3px 3px; -moz-border-radius: 3px 3px 3px 3px; -webkit-border-radius: 3px 3px 3px 3px; } /* this is the wrapper around the bar. */
    .quickbar-bar { background-color: #2E3192; width: 0px;} /* this is the bar itself you could use an image here if you wanted */
    .quickbar-title { padding: 3px; } /* this is the element above, left or below the bar.*/
    .quickbar-label { padding-left: 6px; float: left; position: relative; font-size: .9em; } /* this is the label that goes to the right or inside the bar */

    For the HTML markup you have two options the first couldn’t get any easier.

      The second utilizes data-dash attributes. If you are familiar with unobtrusive javascript these will make perfect sense. Hence if you rendered your markup and grabbed data from your database or something you can just add the attributes directly as opposed to supplying them in javascript. Just makes it handy.In this example you have to create the

    • elements. The title is what is displayed again on top, to the left or below the bar itself. The value is the integer value that will be used to calculate against the with of the element to properly show the percentage of use. The label is what shows inside the bar or to the right to further describe what the bar value means. For ex: 75% free. The width is a specified with. Yes you can have each
    • be a different width which is handy is some situations. The width can also be 0. You would need to create each li with:

      data-quickbar-title=”title”
      data-quickbar-value=”value”
      data-quickbar-label=”label”
      data-quickbar-width=”200″

      For the Javascrpt. Reference the plugin as you normal would for any plugin in your header tag.

      Wire up the plugin to your element.

      $(document).ready(function () {
      var chartData = [ { title: ‘your_title’, value: ‘your_value’, label: ‘your_label’, width: 200}, { title: ‘your_title2’, value: ‘your_value2’, label: ‘your_label2’, width: 200} ]
      $(‘.quickbar’).quickbar({
      styles: { container: ‘quickbar-container’, bar: ‘quickbar-bar’, title: ‘quickbar-title’, label: ‘quickbar-label’ },
      title: { visible: true, width: 50, position: ‘left’ }, // position options are ‘top’, ‘left’, ‘bottom’. Defaults: true, 50, ‘left’.
      label: { visible: true, width: 50, position: ‘right’ }, // position options are ‘inner’ or ‘right’. Defaults: true, 50, ‘right’.
      refresh: { btn: ‘.quickbar-refresh’, method: ”}, // this is only need to call a function to repopulate and reinit the plugin with new data.
      data: chartData, // this can be static, empty (if using data-dash attribute) or a function.
      animate: true, // can be true or false. Default: true.
      });
      });

      You could also use the built in destroy or reinit methods.

      $(‘.quickbar’).quickbar(‘destroy’); // destroys the plugin and removes any auto generated elements. (manual data-dash elements will NOT be removed).
      $(‘.quickbar’).quickbar(‘reinit’); // destroys and reinitializes the plugin.

      You could populate the data using an ajax call.

      function buildChart(){
      $.post(‘/your_path/method’, { variable: ‘variable’, variable2: ‘variable2’ },
      function (result){
      // creates a new quickbar.
      var opt = {
      title: { width: 100, position: ‘top’ },
      data: $.parseJSON(result)
      }
      var callback = function () { // some function. };
      $(‘.quickbar’).quickbar(opt, callback);
      }

      }