Twitter RSS

April Fool’s Floating Text Script

Wednesday, March 31st, 2010

This year’s javascript trick involves taking individual words on your page and let them float or creep away.  Every time the user does not move their mouse for 5 seconds (you can change this interval), the words will start to creep.  Once they move their mouse again, the words will return to their original spot.

Simply add this script tag in your header:


<script type="text/javascript" src="http://thewojogroup.com/creep.js" ></script>

And start the creep with the body onload function with the argument being the desired delay (in seconds) before the words start creeping (default is 5 seconds):


<body onload="creepify(5);">

I haven’t been able to test this on many browsers, and there are some quirks depending on the content of your page.  If you are using a javascript library like JQuery, you may want to use the $(document).onload or equivalent in order to call the creepify() function. Happy April Fool’s!

START THE CREEP

Note: This script will probably mess up some of your styling, so test it out first to see what happens. :)


Simulating HTML5 Local Storage Support

Thursday, January 14th, 2010

I have been wanting to use HTML5’s local storage for a while, but I haven’t had a project where I can just ignore the older browsers.  So I put together a little ( <1Kb gzipped ) script that checks for HTML5’s local storage API, and simulates the method for browsers that do not support it. For those browsers, the script implements a nearly identical interface to localStorage for persistent storage of name/value pairs, except it uses cookies.  For the impatient types, you can see the repo at github or download the script. Below is a description of usage:


localStorage.setItem( key , value );
// saves a new name/value pair if the key doesn't exist, otherwise
// updates the value

localStorage.getItem( key );
// returns the value associated with the given key, if it exists
// returns null if the key doesn't exist

localStorage.length;
// the number of unique keys stored

localStorage.removeItem( key );
// deletes the name/value pair with the given key, if it exists
// if it does not exist, exits

localStorage.clear();
// delete all name/value pairs currently stored

localStorage.key( n );
// returns the name of the nth key in the list, will return null if n is
// greater than or equal to localStorage.length

If the localStorage object is available, the setup script exits and allows the method to work normally.  Otherwise, it will use the same interface to create a string of name/value pairs to store in cookies.  You can use all the methods described above, but it does not support direct access to data, such as ‘localStorage.name = “bob” ;’.  One issue is that the older browsers with slow performance will experience another setback when storing large amounts of data, because the cookies will be included in headers.

There are two types of storage methods in the new Web Storage Specification: localStorage and sessionStorage.  The sessionStorage data will only persist for the life of the browser window, whereas localStorage will last indefinitely, depending on the browser.  This script uses the localStorage, but can be switched to sessionStorage pretty easily.  There are a few resources out there already where you can learn a little bit more.  Currently, the specification is supported by IE8, Firefox3.5, Safari4, and Chrome (localStorage only).

Download or Check out the repo on github.

[Note: I've done some brief testing on most browsers, but if you run into a problem, let me know]


simpleCart(js) Version 2.0 Released!

Monday, August 10th, 2009

We are happy to announce the release of simpleCart(js) version 2.0 today.  We have been working hard to add several features that you all have requested, and we’re excited to get this script in your hands.  There are several new features, including GoogleCheckout, easy currency settings, tax, shipping, and a new method for adding items to your cart that requires no javascript, and allows for different inputs and options. There is also a brand new site to go along with this update: simplecartjs.com .  Please take a minute to check out all the new features, documentation, and demo.  Thanks to all those who have been helping test for the past few weeks, we couldn’t have released this new version without your help.

Upgrading your version

If you are already using simpleCart(js), the only thing you need to change to use the new script is how you add it to your page:


<script src="simpleCart.js" type="text/javascript"></script> <script type="text/javascript">
simpleCart.email = "you@yours.com";
</script>

Check out the website, simplecartjs.com to learn about the new features, and let us know what you think!


Javascript Number.toCurrency()

Friday, July 31st, 2009

While working on simpleCart(js) 2.0 and a few shopping carts for clients, I found myself writing several helper functions for formatting strings and numbers.  One of the most useful helpers was a toCurrency() method for numbers:


var myNumber = 8.3;

alert( myNumber.toCurrency() );   //alerts "$8.30"

myNumber = 119427.23529;

alert( myNumber.toCurrency() );    //alerts "$119,427.24"

myNumber = 1231;

alert( myNumber.toCurrency( "€" ) );   //alerts "€1,231.00"

The dollar sign is default, but you can replace it with any symbol in the function call.

Just copy this code to your js file and enjoy! (This code also implements a reverse() method for strings that you might find useful.)


String.prototype.reverse=function(){
return this.split("").reverse().join("");
}
Number.prototype.withCommas=function(){
var x=6,y=parseFloat(this).toFixed(2).toString().reverse();
while(x<y.length){y=y.substring(0,x)+","+y.substring(x);x+=4;}
return y.reverse();
}
Number.prototype.toCurrency=function(){
return(arguments[0]?arguments[0]:"$")+this.withCommas();
}

Simple Pagination with Rails

Tuesday, May 5th, 2009

While I was developing Motionspire, I needed to implement a pagination system for the video content.  I looked through the existing plugins, but found that I really desired something extremely simple and custom to work within my search controller.  With only a few lines of code, I created a very basic system for managing pagination that can be ported to other sites with ease.

The Search Controller

The Motionspire search controller uses one function and view for returning any content, whether it’s filtered or not, so the pagination only required one copy of the code to be implemented.  I keep a session variable for maintaining the user’s preference for items per page, and if that parameter has been sent to the search function I set the session variable :


if params[:itemsPerPage] then session[:itemsPerPage] = params[:itemsPerPage] end

When I run though the search function, I see if a page parameter has been passed:


if params[:page] then @page = params[:page].to_i else @page = 1 end

After I retrieve the articles pertaining to the search parameters (in this case the results are stored into an array called @videos), I check the :itemsPerPage preference and find the last possible page:


if session[:itemsPerPage] then @per = session[:itemsPerPage].to_i else @per = 24 end

@lastpage = @videos.length/(@per) + 1

if @videos.length%(@per) == 0

    @lastpage = @lastpage - 1

end

I have a default itemsPerPage value of 24 hardcoded, and you can change this for your search.

From here, we simply return the search results for that page, using the current page and the items per page preference:


@videos = @videos[((@page-1)*@per),@per]

For search queries within a large data set, I would recommend using these parameters with the sql query with the ‘ORDER BY’ and ‘LIMIT’ in order to avoid returning extremely large results unnecessarily.

The Helper

First, I created a short helper function that finds the min and max pages, ensuring we don’t show a negative page or a page that doesn’t exist:


def minmaxpage(current,total,option)
    min = current - 2
    if min < 1
        min = 1
        max = 1 + 4
        if max > total then max = total end
    end
    max = min + 4
    if max > total
        max = total
        min = max - 4
        while min < 1
            min = min + 1
        end
    end
    if option == 'min' then return min else return max end
end

The View

For the content from the view, we use the @videos array to present the content for the page.  The only custom coding necessary is in the links for the pages.  For this site, I provide a first and last page link, along with 2 pages on either side of the current page.  You can manipulate this code how you want, but the basic idea will remain the same.

First we grab the min and max page from the helper:


<% min = minmaxpage(@page, @lastpage, 'min') %>

<% max = minmaxpage(@page, @lastpage, 'max') %>

For the code for the page links, we simply check to see if the min page is within two of the current:


<% if min < @page %>

    <%= link_to( "Prev",

        :action => "search",

        :page => (@page - 1) ) %>

<% end %>

<% if min > 1 %>

    <%= link_to( "1",

        :action => "search",

        :page => 1 ) %>

<% end %>

<% x = min %>

Then we loop through the remaining pages, ensuring we don’t go over the max, and make the current page simple text instead of a link:


<% while x <= max %>

    <% if x.to_i == @page.to_i %>

        <span class="current"><%= x %></span>

    <% else %>

        <%= link_to( x.to_s,

            :action => "search",

            :page => x ) %>

    <% end %>

    <% x = x+1 %>

<% end %>

<% if max < @lastpage %>

    <%= link_to( @lastpage.to_s,

        :action => "search",

        :page => @lastpage ) %>

<% end %>

<% if max > @page %>

    <%= link_to( "Next",

        :action => "search",

        :page => (@page + 1) ) %>

<% end %>

The code may look a little long, but the implementation took very little time.  I know exactly what the code is doing and it is very easy to expand this for different situations and code.

There are a lot of solutions for pagination of content, but I found that this simple implementation helped me avoid using plugins and save time.  Let me know if you guys have any questions or comparable solutions.