Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Sass CSS with Compass using Grunt Not Working on Windows

My team is using AngularJS, Node.js, Grunt, Sass CSS via Compass, Yoeman, and a few other web toolsets.  The other day when running the serve process to generate the css output from Sass CSS, the css wasn’t able to generate.  It turned out that Compass was setting the permissions on the .tmp folder where it puts the CSS to a state that didn’t all the process to write the file, hence a Permission Denied error.  To fix this issue I followed the StackOverflow thread http://stackoverflow.com/questions/22596760/yeoman-error-errnoeacces-on-line-897-of-c-permission-denied which did these steps.

Open a command prompt and run the following.

  1. gem uninstall sass (if you have multiple version, select all)
  2. gem uninstall compass
  3. gem install compass --pre
  4. gem install sass --pre

Installing Node.js and Other Packages

Keeping up with technology can be a job in itself.  Learning is fun, but is quickly forgotten so writing things down can always save you time later.  This thread goes over various was of installing Node.js and other packages.

Installing Node.js

There are 2 ways in which you can install Node.js.  Node.js comes with node package manager now so it will not need to be installed independently.

Installer (recommended): Go to node.js.org and use the installer for your OS.  Run the installer.

Homebrew (Mac only): Run the command “brew install node”.  You will have to have homebrew installed.

 

Other Node packages t

Installation will use node package manager.  You can list the node modules for your node application by listing the directory of “node_modules”.

Express – web application framework for node

npm install -g express --save

NOTE: once you create a application with express (i.e. express AppName) you will have to navigate to AppName folder and run the command “npm install” to install the components defined in node’s package.json.

Yeoman – front end tool focused on scaffolding (yo), building/testing (grunt), and dependency management (bower)

npm install -g yo --save

npm install -g generator-webapp --save

coffee-script – scripting language that builds down to javascript.

npm install coffe-script --save

node-dev – a tool for node that will monitory files and auto restart the node app when a file has changed.

npm install node-dev –save

NOTE: When using this you will want to separate development dependencies from production ones.  In the package.json, you can create a “devDependencies” like so:

{
"name": "application-name",
...,
"dependencies": {
"express": "2.5.8",...
},
"devDependencies": {
"node-dev": "~0.2.2"
}
}

mocha – javascript test framework for node

npm install mocha –save

NOTE: put this in your dev dependencies

REQUIRES: request

request – modeule that simplifies the process of making http calls

npm install requets --save

Redis – open source advanced key-value store

npm install redis hiredis connect-redis --save

REQUIRES: Installation of Redis backend.  On a Mac use homebew “brew install redis”, Windows see redis.io.

connect-assets – transparent file compilation and dependency management for Node’s connect framework

npm install connect-assets --save

socket-io – simplifies the use of IO on all browsers.  See WebSockets for information on this topic.

npm install socket-io --save

AngularJS – front end web application framework dealing with models, views, collections, and events

npm install angular --save

Backbone – front end structured for web applications dealing with models, views, collections, and events

npm install backbone --save

RELATED: Marionettejs (npm install backbone.marionette --save)

ASP.NET CollapsiblePanelExtender Printing Content

The other day I was working with the ASP.NET Ajax toolkit’s CollapsiblePanelExtender and have the toughest time getting the content within the panel to print.  I found that there were 2 issues going on: 1)  you have to expand you panel before you print, and 2)  there is some CSS magic that you need to do to get all the content to show.  For the first issue, you have to expand all the panels before you print, which you can do using some JavaScript, unfortunately you can’t fire this when the user select File^Print.  The second issue I resolved using the CSS print media type, which I have an example of the principle here Printable Web Page. 

Expanding Collapsible Panels

This can be achieved by a little JavaScript.  In my situation the user’s wanted a toggle in the UI, I used a check box but a button can do the same thing.

1.  Create the UI toggle item that will fire JavaScript onclick event.

<input type=”checkbox” onclick=”toggleCollapsibleSections();” />

2.  Create the JavaScript that will expand/collapse the panels.  Note I’m using jQuery here to find the elements and that the ID of the collapsible panel is the client ID for the CollapsiblePanelExtender.  If you’re using .NET 4.0 you can set the extender’s ClientIDMode to Static otherwise you will have to either use CSS class to find extenders you want or spit our the X.ClientID where X is the extender control.

function toggleCollapsibleSections() {
    var isChecked = $("#toggleCheckbox").attr("checked");
    if (isChecked) 
        expandSections(true);
    else 
        expandSections(false);
}

function expandSections(doExpand) {
    if (doExpand) {
        $find("MyCollapsiblePanelExtenderClientID")._doOpen();
        // + all other section i want to open
    }
    else {
        $find("MyCollapsiblePanelExtenderClientID")._doClose();
        // + all other section i want to close
    }
}

Printing Collapsible Panel Content

This was a tough fix.  In a nut shell the CollapsiblePanelExtender applies a inline style “overflow” to the div that wraps you content.  This causes the printing to cut off the content within you section if the content is high enough.  The way to solve this is to define a overflow style for all div’s in you print media CSS file.  See Printable Web Page on details about defining and using print media CSS.  The CSS is listed below.  Notice the usage of the “!important” this will override any inline styles that the ajax toolkit has applied.

div { overflow: visible !important; }

Find jQuery Autocomplete Input ID

The other day I was working with jQuery autocomplete where the autocomplete was being applied to a collection of input elements.  One of the issues I was running into was that I needed a reference to the input that the automplete was extending during the execution of the select event.  The way to do this is to store a reference to the input inside the function executing the select event, in essence create a closer.  Below shows how this done, the call to $(this) resolves to the input that is being autocompleted.

$(".all-my-autos")
.autocomplete({
source: "auto-me.php",
minLength: 2,
delay: 500,
select: function (event, ui) {
var input = $(this); // reference to input
// do what you need with input...
alert(input.attr('id'));
}
});

Visual Studio 2010 Javascript Outlining Plugin

The other day my colleague Ben Martin, a somewhat developer tool aficionado, sent me this great JavaScript enhancement plugin for Visual Studio.  I’d have to say, it is one enhancement I’m surprised was not already in Visual Studio.  The plugin adds outlining and minimizing/maximizing code blocks, the same that you would get in a C# code file.  It is a much needed enhancement and a must for anyone who is doing JavaScript coding.  I think the only thing I noticed that would be nice to have in it would be the Ctrl+M+O hotkey which minimizes all code blocks.  You can download the enhancement here.

reCAPTCHA Custom Styling

CAPTCHA is one of those neat little items that help prevent automated attacks on sites that have form submissions such as registration or blog posts.  I was searching for a way to use CAPTCHA in a ASP.NET MVC site, but what I found can be applied to any coding tool like PHP, Java, Ruby, etc.  I followed this excellent blog Using ReCaptcha with Asp.Net MVC for most of the backend code.  Once I got it working I realized that the default generated CAPTCHA widget didn’t go well with the site’s color palette.  Fortunately you can change the widget’s appearance.

Solution:

1.  Place this snippet before the form element that contains the CAPTCHA widget.  Note that I went with the “clean” theme.  Other themes are possible, see full reference here.

<script type="text/javascript">
var RecaptchaOptions = {
theme : 'clean'
};
</script>

2.  Somewhere in your form element place the following HTML and script reference, this is a barebones approach.  In the script reference don’t forget to replace “your_public_key” with the public key you got from signing up for API key.

<script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k=your_public_key"></script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=your_public_key"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>

3.  If you want to internationalize your CAPTHCA widget, you can include the additional div elements shown here and add the following to the RecaptchaOptions shown in step 1.  You’ll have to insert the translated text of your choice dynamically.
 
<script type="text/javascript">
var RecaptchaOptions = {
custom_translations : {
instructions_visual : "Scrivi le due parole:",
instructions_audio : "Trascrivi ci\u00f2 che senti:",
play_again : "Riascolta la traccia audio",
cant_hear_this : "Scarica la traccia in formato MP3",
visual_challenge : "Modalit\u00e0 visiva",
audio_challenge : "Modalit\u00e0 auditiva",
refresh_btn : "Chiedi due nuove parole",
help_btn : "Aiuto",
incorrect_try_again : "Scorretto. Riprova.",
},
theme : 'clean',
};
</script>

That’s it.  My widget looked something like the image below.  I left out the some of the customization div elements and went with they’re “clean” look.

Capture

Autocomplete jQuery and JSON Is Now Here

Autocompletion text boxes are one of those nifty little tools that when used in the right setting really add a great user experience.  Just recently I was trying to figure out how to return JSON from a autocomplete call and use jQuery.  Older versions of jQuery only support line break text return values limiting you on what you could return.  So hoping to find something better, I Googled it and low and behold, jQuery UI now incorporates the autocomplete feature using JSON results by default!   As of v1.7, I believe, this is supported.  There is a good blog by Jörn Zaefferer, talking about the work involved in migrating from the old jQuery autocomplete plug-in to the new method.

You can get either download jQuery UI versions or use Google CDN.

Web Site Menus, What To Use?

I have to say that I appreciate all the many people out there that aid all of us non Web UI layout experts with tips, tricks, and how-to posts.  One of the items I have difficulty with when laying out a menu structure for a site that has more than just a main menu, is what type of menu should I use.  Some of the options maybe vertical or horizontal menu,  tree with +/- nodes or drop down menu, etc.  I had this project where, for some reason, they just wanted a list of hyperlinks on the page for the sub menu, but they had to shorten all the names to ~5-10 characters because there were so many, it was hideous.  My friend Aaron Schnieder recommended using a mega menu.  First thing that came out of my mouth was “what the heck is a MEGA menu?”.  It sounds like some combo move in the 90s video game Killer Instinct.  He gave me this link to demo on the mega menu.  I was amazed, it’s so clean and flexible.  Now, the question is should I always use the MEGA MENU?  I think it depends.  In the case of MSDN library which has that side navigator with a gazillion possibilities the mega menu wouldn’t fit, but if you have a decent sub menu that you want your users to see when hovering over the main menu, the mega menu fits like a glove.  The tutorial on Soh Tanaka’s blog is amazing, basically there’s 4 steps:

  1. Html layout  for main menu and sub menu - ul/li structures
  2. Sprinkle of CSS
  3. Dash of jQuery – uses Hover Intent jQuery (very slick), but can optionally be excluded
  4. Very minimal on page load initialization.

jQuery Kicks Ass

If Chuck Norris were a javascript framework, he would be jQuery.  If you spell jQuery in the game of Scrabble , you win for ever.  That’s how awesome jQuery is.  I’ve used many a javascript frameworks, such as prototype.js, mootools, and script.aculus.us, but none have I found so flexible, so light, and so extendable a jQuery.  The core framework is very compact and whatever you need that the core does not provide, you can find a jQuery plugin that will do it.  I’m not really going to go into any examples, this blog is more like a notebook of common plugins that I’ve found very useful.  As a note to Visual Studio users, they have done a excellent job of providing javascript intellescene and now ship ASP.NET MVC with jQuery plus a .js file with all the code commenting.

Date pickers

http://www.eyecon.ro/datepicker/

http://arshaw.com/fullcalendar/ (full calendar)

Validation

http://validity.thatscaptaintoyou.com/

http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Tooltip

http://bassistance.de/jquery-plugins/jquery-plugin-tooltip/

Templating

http://publicityson.blogspot.com/2009/11/dynamic-content-using-html-templates.html

Dynamic Content Using Html Templates

About 2-3 years ago, I was working on this project where I was receiving JSON data from the server then injecting the results into dynamically created content using the built-in JavaScript DOM methods.  It worked alright, but was a pane in the butt.  Lately, I came across idea using client side templates.  The concept of templates isn’t new, but I never thought to embed one in my HTML code.  What is even more cool, is that there are a few approaches to using the templates.  One such approach can be found here on Rick Strahl’s blog.  I saw this gentleman talk at 2009 DevConnections, really cool guy.  His approach is to clone some DOM segment and then update the element values where needed.  This works really well.  As I was searching I came across a second approach that knocked my socks off.  Below describes how this approach is used.  Currently I’m using the ASP.NET MVC pattern with my web pages but this could be done with WebForms, though there might be challenges with client IDs.  There are some helper methods from ASP.NET MCV within the html below, but they should be self explanatory.

Basics steps:

  1. Embed some hidden DOM inside a <script type=”text/html”> tags inside your page document.
  2. Make a JSON request or build an object which will be used as a data source.
  3. Using jQuery and this templating extension, you can inject the data from step 2 into the template.
  4. Insert this data injected template somewhere in your page.

So those are the basic steps, lets see some code.  I’m going to be using a html table as an example because that lends itself to the obvious add a row concept.

1. The html page with embedded template html snippet

<html>

<table id="OrderTable" width="100%" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th />
<th>Quantity</th>
<th>Name</th>
<th>Price</th>
<th />
</tr>
</thead>
<tbody>
<tr>
<td><a href="”/Order/abc1234/Edit/1”">Edit</a></td>
<td> 1 </td>
<td>Some Product</td>
<td>5.50</td>
<td />
</tr>
</tbody>
</table>

<script id="RowTemplate" type="text/html"> 1:
<tr id="${Tag}_Order">
<td><a href="<%= Url.Action("Edit")%>/${Tag}">Edit</a></td>
<td>${Quantity}</td>
<td>${Name}</td>
<td>${Price} </td>
<td><a id="${Tag}_Delete" href="<%= Url.Action("Delete")%>/${Tag}">Delete</a></td>
</tr>

<div id="AddProduct">
<% using (Html.BeginForm("AddProduct", "Orders", FormMethod.Post))
{ %>
<div><input type="submit" value="Add Product" /></div>
<label>Product:</label><%= Html.DropDownList("products")%>
<label>Quantity:</label><input id="Quantity" name="Quantity" type="text" />
<% } %>
</div>

<script type="text/javascript">
$("#AddProduct form").submit(addProduct); // hijax product add form submission using jQuery

</html>
The key part of this html code is the template that is sitting inside the <script> block.  Notice there are some funny ${…} looking items in there.  This will be what our data is bound to, or in other words substituted for.  One thing I’m not diving into too much detail here, is that the events I wired up to the A links have been done in a “hijaxing” manor using jQuery
2.  Make a JSON request in order to get back some data in the form
Since our example form submission will be handled by client side JavaScript, lets look at a simple call.  Below shows the request using jQuery library which will get back a json object.   On successful call, we call the method “addProduct_succss” which will take care of our template data binding.

3 & 4.  Using the jQuery template extension inject the data and append to DOM


function addProduct_sucess(response)
{
// using template libarary, create template object using html snippet
var t = $.template($("#RowTemplate").html());
// response = { Tag:3, Quantity:2, Name:"Snuggy", Price:19.95 }, notice that property names match to template ${...} names.
var row = $(t.apply(response));
// appned this DOM row object to our table
$("#OrderTable tbody").append(row);
}
The jQuery template library will use the html snippet from the <script> block to create a template object.  Then the JSON that was returned will be applied to the template.  The key to remember here is that the JSON’s object properties, such as Quantity or Price, match to names in the template like ${Quantity} or ${Price}, respectively.