Writings, notes, and work of a Boston based designer

Installing Ruby on Rails Plugins via MediaTemple May 10 + 2 comments

written by: ryan coughlin

Good Morning and Happy Mothers Day!

I have been running Ruby on Rails on my Mac, playing around with applications, getting familiar with the framework. I recently started a Ruby on Rails project for a client and I told the client to switch over to MediaTemple, the best decision ever made. All of the controls and support are amazing. I was trying to run this command to install Restful Authentication:

./script/plugin install git://github.com/technoweenie/restful-authentication.git

The main issue to make sure to be aware of is to Electronic Cigarette change to your containers directory using this via Terminal:

cd $HOME/../../containers

If you do run:


You should now see a listing of any containers you have purchased in my case mine returns:


Change directories for you are inside your rails application and now run:

./script/plugin install git://github.com/technoweenie/restful-authentication.git

You should be golden! Hope this helps out some people with any issues they may have. I should also add in that the command will generate your controllers/models, best of luck!

./script/generate authenticated user sessions

How to load data using JSON/PHP using jQuery May 6 + 2 comments

written by: ryan coughlin

I have seen a good amount of people wanting to see learn how to load data on their website using jQuery, JSON, and PHP. I thought I would show a simple example that should give you a jump start to your project.

We are going to use $.getJSON() function, you have something like:

    $.each(data.posts, function(i,post){
          content = '\n';
          content += '' + post.author + '\n';
          content += '+ post.date_added + '\n';
          content += '' + post.post_content + ';
          content += '; 

And example of JSON from the PHP page could look like this below:

{ posts <a href="http://www.primetimecomedyonline.com/">Electronic Cigarettes</a>: [{&quot;id&quot;:&quot;151&quot;,&quot;date_added&quot;:&quot;2009-05-05 13:40:34&quot;,&quot;post_content&quot;:&quot;This is a test post. jQuery!&quot;,&quot;author&quot;:&quot;Ryan&quot;},
{&quot;id&quot;:&quot;152&quot;,&quot;date_added&quot;:&quot;2009-05-05 13:40:55&quot;,&quot;post_content&quot;:&quot;Hey, you got to love Ajax&quot;,&quot;author&quot;:&quot;John&quot;}] }

That JSON above loads two records that will be displayed on to the page.

The results are being pulled from a MySQL database with tables: id, author, post_content, date_added, and author.

I am going to wrap up and article on the jQuery/PHP/JSON comment form with the results loaded on to the page after form submission, stay tuned for a much more in depth explanation of using JSON with PHP and jQuery.

Time for another iGoogle theme? May 5 + 2 comments

written by: ryan coughlin

So i came across my old iGoogle theme I made in the fall and was thinking of making another one. Shockingly, they’re extremely easy to create. Its a large XML document.  I have been working on a new layout for my site. I was thinking of another landscape but similar to the landscape, but different style.
Summer Landscape - iGoogle Theme

I am trying to free my schedule from client work to start working on us manufactured electronic cigarettes the new layout, stil need to work on the move right text, bottom posts boxes, colors, and what the single page is going to look like, all in all its a work in progress. Almost done with a jQuery tutorial on submitting a  comment form and having the results loaded using jQuery/Ajax. The comments on the page are loading using PHP, JSON, and jQuery, very slick. Expect that very soon.

How to use jQuery to Serialize Ajax Forms May 4 + 2 comments

written by: ryan coughlin

When I first started working with jQuery and submitting forms via Ajax, I’ve never really used .serialize() and wasn’t too familiar with it. I started to look in to how it works and what it can do. It can be a huge time saver, especially for larger forms.

Instead of declaring all of your data to be sent using something like:

var fname     = $('#fname').attr('value');
var lname     = $('#lname').attr('value');
     data: “fname=”+ fname + “& lname=” + lname,

For a couple of fields above, that is fine, but what if you were creating a form with a large amount of fields. The last thing you would want to do is want to copy/paste that line 20 times for your field. Instead of grabbing each value of each form blu electronic cigarette field we can use jQuery’s .serialize() to do the dirty work for us, which is a huge time saver. We can use something like:

$(function() {
     $('form').bind('submit',function() { showValues(); return false; });
function showValues() {
     var str = $("form").serialize();

The first section binds the submit to a function. When a user submits the form call the function showValues(), the next bit. We grab the form and attach .serialize() to it. We want to serialize all fields within this form and display what data is going to be sent to the sever. A working demo has been uploaded.

Now with our data serialized it is ready to be sent over to the server side. Using jQuery .serialize() is much more effiecient compared to retrieving the value using .val().

Working with the jQuery live function May 4 + 2 comments

written by: ryan coughlin

The other day, I wasn’t really too acquainted with the .live() jQuery function. I did some research and it finally clicked for me. I put together a quick example that can I uploaded. The basics of the function can be known as:

Binds a handler to an event (like click) for all current – and future – matched element. Can also bind custom events. – (source: jquery.com)

This function is extremely similar to the .click() but .click() will only match elements that are created via the XHTML with DOM is loaded. With that said, using .live() is extremely useful for dynamic websites, where you are creating/removing elements on you’re website.

Lets see the base online blackjack flash example of using .live()

$('a.edit').live('click', function() {
     alert("The power of .live() - dynamically created objects will have bound events!")
     return false;

This code will work for all links that have the class edit, even when new a.link tags are created dynamically after DOM has been loaded. If your code looked like:

$('a.edit-nolive').click(function() {
     alert("Items created via AJAX will be called on using .live()")
     return false;

It would not work on dynamically created items. Lets take another look at the full demo. Hopefully this will clear up any problems with understanding how the jQuery .live() function works in comparison to the .click() event. Like to see something else like this? Drop me a line.

Active Record Already Activated May 4 + 2 comments

written by: ryan coughlin

After spending hours and hours staring at line after line of SSH into my MediaTemple Ruby On Rails Container, I finally found a solution for this stubborn error that kept developing in my mongrel log on application start:

/home/XXXXX/data/rubygems/lib/rubygems.rb:149:in `activate’: can’t activate activerecord (= 2.3.2, runtime), already activated activerecord-2.1.0 (Gem::Exception)

I have tried a whole slew of commands to try and fix this. First, I tried running:

gem cleanup

Still got that same error when I tried starting my application I made sure that my environment.rb was called the correct version of Rails that I had installed. This command seem to get me in the right direction:

rake rails:freeze:gems

Before running this, call the following code from your applications root directory:

rm -rf vendor/rails/

This will remove the folder “rails online blackjack money“, then you can continue with running the rake command. After running rake freeze, I got an error, saying it couldn’t find any rake files. I got this output:

Freezing to the gems for Rails 2.3.2
rm -rf vendor/rails
mkdir -p vendor/rails
cd vendor/rails
ERROR: Gem ‘activesupport’ not installed.
mv activesupport
rm -rf vendor/rails
rake aborted!
undefined method `to_str’ for nil:NilClass

Specifying a version to the rake freeze command this work like a charm, I simply ran:

rake rails:freeze:edge RELEASE=2.1.2

Started my application, checked my mongrel log, no errors on start up. I browsed to my URL and it worked. Hopefully this can help you fix your problem and relieve any headaches. If I missed anything that can help other people out, let me know. The joys of coding continue…

New Layout and Trip May 4 + 2 comments

written by: ryan coughlin

Its been a very long time! I have been extremely busy with the end of the school year with finals as well as client work up to my eye balls. I have been working on a new layout for ryancoughlin.com and you can check a quick preview here: http://ryancoughlin.com/nightday/

If anyone has any suggestions, please feel free. Still needs alot of work. My goal is to get this up fairly soon. The site needs a face lift, looking a bit dull.

Along with the new layout, I have some blog posts that I have been working on, so keep your RSS feeders ready. If not, head over to the subsribe box and grab my Feedburner URL.

I am going to be headed off to Europe on May 13, starting in England, then headed to Greece to end my trip. Im going to do my best to keep at blog posts as well as keeping my flickr updated. Expect lots of pictures. I’ll do my best to keep it updated.

Stay tuned for updates.

5 Services For Short, Tiny, Small, and Compact URL’s Apr 3 + 2 comments

written by: ryan coughlin

Everyone is using Twitter as a means to promote their blog posts or articles. Since Twiter only limits each tweet to 140 characters, which doesn’t leave you alot to say you have a new blog post and the title, along with the URL for users to check it out. Thanks to the expansion of Twitter, more and more tiny URL services have been released. Below is a collection of 8 that i have found and used in the past.

Some are the more well know such as Ping.fm and TinyURL, but I found a couple others that do the job just fine. Check out the list below and post if you have any others you use!

Example URL: http://tinyurl.com/c35n8e – 28 characters
Organic URL:
http://www.ryancoughlin.com/ – 27 characters

This is by far one of the mostly used and original tiny URL services out there. Generates a fairly small URL. This service makes it great for posting long URLs on twitter or any other social media service. Shows you the original and the number of characters, which is a nice added bonus. Also allows you to create your own tiny URLtinyurl alias instead of having the service generate one for you.

Example URL:
http://✩.ws/ꉚ – 12 characters
Actual URL: http://www.ryancoughlin.com/ – 28 characters


This is a fairly new tiny URL service out there, but what makes this one differen than the others, is that is uses symbols instead of random characters for instance, it uses arrows and stars. There is a dropdown to the left of the input field for your URL where you can choose what symbol you would like to use for your URL.  Once you create the URL, it has a shortened Pokies version and then a Twitter preferred version as well. Along with those two, it has a TinyURL version and the original. These are one of the smallest URL’s I have seen.

TinyURL Creator – Firefox Add-on
This uses the TinyURL service but allows you to create URL’s at your fingertips, uses the same great original service. One of many excellent Firefox Add-ons

Example URL:
http://ping.fm/laMe – 19 charachers
Actual URL: http://www.ryancoughlin.com – 27 characters

pingThis one is another tiny URL service, but it is much more than that, so I figured it would make the cut. You can register all of you social networks and have them update all at once, which makes this service extemely useful! Post to WordPress, Twitter, Blogger, MySpace, Facebook, the list is endless. A must see service for you social media junkies.

Example URL: http://turl.ca/fkhkzw – 21 characters
Actual URL: http://www.ryancoughlin.com/ – 27 characters


Yet another service, very simple and straightforward, paste in your URL, let it generate a random URL or type in your own alias. The developer also created Pastebin, which is extremely handy for pasting code with syntax highlighting. Supports CSS/HTML/Java/PHP/SQL and much more. Simple layout makes this service very usable.

There is a list of the top 5 services that I have used to help shorten my URLs. This list could go on and on, there is many copy cats out there, but why reinvent the wheel. If you search in Google there are pages and pages of other sites that create tiny URLs. The problem with the smaller ones is that they are flooded with ads. If you have another service for shortening URLs share it and ill add it to the list.

Create a jQuery Accordion – remain open after page load Mar 30 + 2 comments

written by: ryan coughlin

I am currently working on this site for a client: http://www.hornedpout.com/ – a very basic portfolio website for a designer/writer. I didn’t want to use the bulky code of the jQuery UI so I decided to use the smaller version, below:

$(".menu-header").click(function() {
        return false;

The HTML would look something similar to:

<h2 class="menu-header">art gallery</h2>
	<li class="item"><a title="Traditional Art Work" href="?c=traditional">traditional</a></li>
	<li class="item"><a title="Digital" href="?c=digital">digital</a></li>
	<li class="item"><a title="Posters" href="?c=posters">posters</a></li>
	<li class="item"><a title="Icons" href="?c=icons">icons</a></li>
	<li class="item"><a title="Fonts" href="?c=fonts">fonts</a></li>
<h2 class="menu-header">verse</h2>
	<li><a title="Poems" href="?c=poems">Poems</a></li>
	<li><a title="Stories" href="?c=stories">Stories</a></li>

That code will use jQuery’s toggle() function. When the user clicks the h2 tag it will close all elements until the next
tag. This snippet is very handy for creating a quick accordion effect, this can also be found on the jQuery’s documentation

Now we have the guts sorted out, but the problem is if you travel to another page within that category, it will close. I’m sure you want to check out the code that is going to do this.

Keep that open! Pokies

var matches;
     if( matches = (new String(document.location)).match(/?c=w+/) ) {
        $("a[href=" + matches[0] + "]").parents("ul").toggle();

The code above is fairly straight forward. The first line checks to see if we already have a sub-menu open. It evaluates by looking at the current pages URL “?c=page_here”.

The latter part of the code. Now that we grabbed the current URL of the sub-menu, we can use this to find the parent menu which is the
ul and display it:

$("a[href=" + matches[0] + "]").parents("ul").toggle();

The quick fix to keep your accordion block open while traveling to different URLS. To achieve the URLS of “?c=page”. I am using this PHP code below save it as index.php, also create a header.php and a footer.php.

Give it a shot, hope that this can work for you, it did wonders for my project. Also thanks to Kent, for helping me. If it did work post some examples!

jQuery Timeout Function Jan 22 + 2 comments

written by: ryan coughlin

UPDATE: Edited the code thanks to Adrian Green. Thanks for the comment

jQuery does offer callbacks for most of its functions, but what if you want to delay or timeout a certain effect or function there isn’t a function made for that. This article should help you achieve that.

Old School JavaScript

I have been trying to search for a nice and reusable way to use jQuery to timeout effects or functions. We are familiar with using the traditional JavaScript function setTimeout():

setTimeout (function,timeout);

After putting in some data we can come up with something like this:

setTimeout (showBox(),2500);

Remember that the value 2500 is in MS (milliseconds), we equates to 2.5 seconds. When this function is called, it will execute 2500ms later. I was using this for one of my projects where I wanted two effects/functions not after, but during. I could have used very handy jQuery callback and load in a function, but it would have been executed after the first function is completed.

Let’s Start Delaying Effects – The Code

Lets jump right into the belly of the beast and view the code to call our handy demi moore pokies jQuery timeout function. Essentially we have a small jQuery plugin. We define the function as: $.idle()

jQuery.fn.idle = function(time){
	var i = $(this);
		}, time);

You see on the first line above we create the idle function: jQuery.fn.idle. We created the variable I to store $(this), which is going to be element that is running the $.idle(); function.

We then use the jQuery queue(); function whose documentation can be found on the jQuery website. Then we attach the $(this); variable we created called: i to it, and create the setTimeout(), which then uses dequeue(); with our variable connected to it.

The last part, where we create the time parameter for the function, so we call the following code and:


time gets replaced with the user input of 2500ms to the function. Say if you want to call a function you can use it in this context instead of the messy old fashion setTimeout(); function.


The above simple reads: fade in my element, then wait 2000ms, slowly fade out the same element. BOOM! There it is, the quick n’ dirty method to delaying functions using jQuery.

Quick And Clean Bold Text Dec 24 + 2 comments

written by: ryan coughlin

There are tons and tons of text effect tutorials out there, but sometimes the simplest ones make the best presentation. I opened up Photoshop earlier and played around with some Blending Options. Very simple tutorial to create some quick and clean bold text. The final results will look like below:

Bold Text - Final

The font that I am using for this tutorial is called Kabel and can be downloaded for free. You can click the images to view them full size to see the details for the Blending Options. Lets get started.
1. Create a new Photoshop file, doesn’t matter what size. Default is fine.
2. Create some text on your page like below Pokies:

Bold Text - Step 2

3. Lets sart by adding some Blending Options to the text layer. Right click on the layer and choose “Blending Options…” Lets add a Drop Shadow to give it some “pop.

Step 3

4. Now that we have added some Drop Shadow to our text. We are going to add a small Inner Shadow to the text, and we are going to use white (#FFFFFF), give it a strong but subtle outline appearance.

Step 4 - The Inner Shadow

5. Now the last step, a Gradient Overlay to seal the deal. For the colors, I did black -> white, with the opacity at 38%

Step 5 - The Gradient

Told ya, it was quick! Check out the final result below. Enjoy and Merry Christmas!

Final Image

jQuery Search And Highlight Dec 20 + 2 comments

written by: ryan coughlin

I was sitting in class and wanted to come up with some simple way to add a inline same page ajax search on a website. I came across the jQuery selector :contains(text), check out the documentation for this. Now the to the final product, lets check out the demo. We are going to have our main components for this:

  • The form (1 input and submit)
  • The :contains selector
  • The fadeIn() effect
  • The addClass()

The approach for the code is going to be like

  • User will enter term in form
  • Save data to a variable
  • Place variable in to :contains selector
  • Fade in the highlight class (using fadeIn() and addClass())

See, there it is simple? Just about! Next lets take a look at the jquery


		// start variables as empty
		var term = "";
		var n = "0";

		// hide the results at first
        // grab the input value and store in variable
        term = $('#term').attr('value');
		console.log("The value of term is: "+term);


		if($('#term').val() == ""){
			$("p.results").fadeIn().append("Enter term in field above");
			return false;
			$('div.container :contains("'+term+'")').each(function(){
				$(this).html($(this).html().replace(new RegExp(term,'g'), '<span class="highlight">'+term+'</span>'));

			// how many did it find?
			n = $("span.highlight").length;
			console.log("The there is a total of: "+n);

			if(n == 0){
				$("p.results").fadeIn().append("No results were returned");
				$("p.results").fadeIn().append("<strong>Returned:</strong> "+n+" result(s) for the search term of: <em><strong>"+term+"</strong></em>.");
			return false;

And now the HTML structure:

<div class="container">
<div class="span-24">
<h1>Welcome to my site!</h1>
<hr />
<form id="search-highlight" action="#" method="post">
                                <label>Search Term:</label>
<input id="term" class="text" name="term" size="25" type="text" />
<input id="submit" name="submit" type="submit" value="Search and Highlight" />
<hr />

Kind of a late start here today. I have been reading this book online lately called Learning Rails that covers version 2.0 unlike most of the books that are out there. I was able to follow and understand this book to guide me through Rails and its done wonders. I haven’t seen to many typos and the code is easy to understand. There is one chapter that floats away from the rest and its a bummer because its the rails and Ajax section, but besides that, its a great learning tool.

						I released an Illustrator tutorial yesterday on creating nautical floatie buoys, a simple and straight forward tutorial. Let me know what you think!

						I was talking to Richard Worth and I am going to be writing a post on working with the jQuery UI and implementing the draggables and selectables together, which is very interesting. I have tried this approach about a year ago with Worth, but it was kind of buggy, Richard released a working version that I will be covering and hopefully try to work it in to the UI API. So stay tuned for that post.

						I am also going to be working on some other posts overtime working with jQuery and various ajax methods and functions. Loading data, displaying data, and all sorts of other goodies

						I have been making small modifications to the site, as you can see I added in the top menu bar, and I know it is broken in IE, im on it! I will be working in a home made small jQuery menu to bring down subcategories of what you see up top.

						Have an idea for a post that you want to see on here? Let me know</div>

Now that we have the outline of the code that we will be using, lets breakdown the bulk of it. If you notice we have the click event handler, which means that the code will not execute until someone has pressed the submit button. The first couple of real pokies online lines take care of initializing of the script.

var term,n;
// hide the results at first
// grab the input value and store in variable
term = $('#term').attr('value');
console.log("The value of term is: "+term);

I have commented the code for it is easier to retain the information when you come back for future reference. So the first two lines just sets two variables term and n. The next line hides the p.results element and empties it, our results after form submission will be loaded in here. Lets come back to the variable that we created we set term to whatever the value that was entered in the input box. We are going to use the console.log to make sure our variable is receiving the data.

Lets make it highlight.

The next section of the code is going to to reset the and remove all span.highlight classes for when you enter another term you will only have the new results entered via the form and not both old and new terms.


The code is going to run through each of the span.highlight and manually remove the tag. This will be executed every time the form is submitted. Its main purpose is to clear the results. The next part is a quick validation making sure that the form cannot be submitted without some type of data, this is the first section of the conditional:

if($('#term').val() == ""){
    $("p.results").fadeIn().append("Enter term in field above");
    return false;

That part reads if the element #term returns empty, then fadeIn() and append() text. The line after adds the class error to the input field to give us as red border indicating there has been some type of error. The return false is in place for the form is not submitted. The latter of the conditional will look like:

    $('div.container :contains("'+term+'")').each(function(){
        $(this).html($(this).html().replace(new RegExp(term,'g'), '<span class="highlight">'+term+'</span>'));

This occurs when there is data in the input, and it takes the term and we find it using :contains, it runs through each element and replaces the text by wrapping a span tag with the class highlight around the term. After, it finds each of those elements and fades them in.

Displaying our results

The last part is going to display our results, it is going to tell us:

  • The term we searched for
  • How many results were found

Lets take a look at the code:

// how many did it find?
n = $("span.highlight").length;
console.log("The there is a total of: "+n);
     if(n == 0){
         $("p.results").fadeIn().append("No results were returned");
         $("p.results").fadeIn().append("<strong>Returned:</strong> "+n+" result(s) for the search term of: <em><strong>"+term+"</strong></em>.");
     return false;

We are going to retrieve the number of results returned by storing it in the variable n and searching for every span.highlight element and using .length() to retrieve the amount. I have added the console.log() to see what is going on in the back end.

The next part is a simple conditional if n returns no results, then fadeIn() and append() text – “No results were found.” If results were found, then do the same but tell us how many were found and what term the user searched for.

There you have it, a very quick and clean same page search and highlight using jQuery. If you have any recommendations or other features you would like to see, drop a comment or email me. What did you think of it ?

Dunks or Starbucks – Who Comes Out On Top Dec 19 + 2 comments

written by: ryan coughlin

This one thing that seems to a rather large debate, which is better?

  • Dunkin Donuts
  • Starbucks

[poll id="1"]

Dunks or Starbucks

Everyone has their own opinion on why they like one or the other, so I thought I would see what everyone else thinks of this Buy Viagra topic. So…which one is it? Please share this!

You can say that Starbucks does not have the breakfast sandwiches or the donuts, and then you have Dunkin Donuts that does not carry have those very tasty cakes and pastries like Starbucks.

Happy Holidays!

Busy…Busy Dec 14 + 2 comments

written by: ryan coughlin

Hey everyone! I have been extremely busy with the past couple of weeks due to the end of the semester coming and trying to get my finals and projects out of the way. Just about done with my ASP shopping cart application and my usability project. I am just about done with the fall semester, so expect some posts here soon in a week. I also meant to post my iGoogle theme I created, its nothing crazy, but thought I would make some fun of it. Try it out!iGoogle Theme - Summer Landscape

If you have any ideas or requests that you would like to see, please let me know, drop an e-mail or comment.

Finally updated my WP and I love the new interface so far, they did a great job on it.  Install went smooth as always.

I am currently working on a same page ajax search and highlight script using jQuery, it is almost done, so stay tuned. I am also going to make some tweaks to the layout, I need more color on this temporary one, you will probably be seeing some changes over the next couple of weeks.

Take care! Cheers.


Combining Selectables And Draggables Using jQuery UI Nov 23 + 2 comments

written by: ryan coughlin

There are two powerful and fun elements that the jQuery UI provides. When both of them work together you will be able to come up with some creative web application uses for them. The two I am going to be covering are:

I am sure you all want to see what the final product will look like, check it out.

To start working with the jQuery UI you are going to need to add the following files to the head of your document:

  • jquery-1.2.6.min.jsthe main core jquery framework
  • ui.core.jsthe UI core javascript
  • ui.draggable.js - the draggable javascript
  • ui.selectable.jsthe selectable javascript

Before we get started let me just say, thanks a ton to Richard Worth who has helped develop the jQuery UI and provided a ton of help to me last year trying to get this to work, and boom here is the working copy, you can find Richards blog here.

The jQuery UI adds classes for different mouse events, for instance:

  • jQuery UI Draggable
    • .ui-draggablethe class it adds you when create the draggable(); object
    • .ui-draggable-dragging - the class it adds when you are dragging the object around the page
  • jQuery UI Selectable
    • .ui-selectee - the class it adds when you create the selectable(); object
    • .ui-selectablethe class it adds when you select the object
    • .ui-selecting – the class it adds when you click and start to create the bounding box around the elements you wish to select, once you let go, it becomes .ui-selectable

That is the basic structure how how the jQuery UI draggable and selectable generates classes to manipulate change for each action.

I am going to be using console.log(); to report what the code is doing after different steps throughout the page. Make sure you have Firebug installed if you are on Firefox. If you are unsure what console.log() does view the documentation. Be sure that if you use this technique in a real world example, remove the console.log() functions to decrease page loading time. This neat little function allows us to see what our code is doing, we can call:


When we open up the page and open Firebug, it will print out what the variable contains, it is a great tool for debugging, keep it handy.

Now that we have the understanding on how it works with different classes, lets start looking at the code that makes it work. I have commented it to make it easier for you to translate on your own time.

The first bits of the code

// creates the selected variable
// we are going to be storing the selected objects in here
var selected = $([]), offset = {top:0, left:0};
console.log("This is the value of selected when it is created " +selected + "");

As you can see from above, our first line creates the variable selected and is able to store numerous values because we are setting up an array for this variable. And the offset, resets the top and left values. If you use console.log it will output: Object length=0 prevObject=Object jquery=1.2.6 notice the length is 0 that is fine we haven’t selected any items yet.

// initiate the selectable id to be recognized by UI

This part above, calls the selectable to generate the selectable region. NOTE: that #selectable is container and is the box not each element we are selecting.

The following part is important because, this is the where we start to hook up selectables with the draggables.

// declare draggable UI and what we are going to be doing on start
$("#selectable1 div").draggable({
     start: function(ev, ui) {
          $(this).is(".ui-selected") || $(".ui-selected").removeClass("ui-selected");
	  console.log("The value of 'this' currently is: "+this);
          selected = $(".ui-selected").each(function() {
               var el = $(this);
	       el.data("offset", el.offset());
	       $(this).text("Selected and dragging object(s)");
offset = $(this).offset();

The part below, tells the draggable UI to create every element within to have dragging.

$("#selectable1 div").draggable({
$(this).is(".ui-selected") || $(".ui-selected").removeClass("ui-selected");
console.log("The value of 'this' currently is: "+this);

This next section above resets the select and drag, by removing the ui-selected class, when we output using console.log, to see the value of this is The value of ‘this’ currently is: [object HTMLDivElement].

selected = $(".ui-selected").each(function() {
     var el = $(this);
     console.log("The value of el is: "+el);
     el.data("offset", el.offset());
     $(this).text("Selected and dragging object(s)");

Now we are finally working with the selected variable we created at the start of this, we are to run through each element with the class of ui-selected. We are going to be storing the value of $(this) in the variable el, to make it easier to call and to work with the offset(); property later on.

el.data("offset", el.offset());
$(this).text("Selected and dragging object(s)");

We are going back to out el variable and working with the data object and the offset object. The offset object returns two integer values: top and right. The definition of the offset(); from the jQuery documentation is: Get the current offset of the first matched element relative to the view port.

The other line Viagra, changes the text of the elements to let us know that we have selected and are now dragging the objects stored in the variable selected.

Now that we have called offset we want to store it in the variable offset, for each DOM elements selected. The code that follows this part is below:

console.log("The new value of selected is now "+selected);
offset = $(this).offset();
console.log("The value of top value is "+offset.top+" and the left value is "+offset.left);

We have another console.log() to print out the selected value and it is storing the DOM element. Next we create the variable offset and store the offset() of the elements, I have printed the top and left values using console.log() above, the output is similar to: The value of top value is 207 and the left value is 672.

The next section below is the section of code that handles what is going to go on while we are dragging our selected elements. This part is also very important because we are bringing back the values of offset with the current values of the draggable ui, it stores the ui properties in ui.position.top and ui.position.left. Further down the code we will use the offset values to update the CSS top and left properties of the selected elements.

drag: function(ev, ui) {
     var dt = ui.position.top - offset.top, dl = ui.position.left - offset.left;
     console.log("The value of dt is "+dt);
     selected.not(this).each(function() {
          var el = $(this), off = el.data("offset");
          el.css({top: off.top + dt, left: off.left + dl});

We are creating the variable dt on the second line there and this value is equal to ui.position.top – offset.top and we are also creating the variable dl that is dl = ui.position.left – offset.left. So we have:

  • var dlworking with the x axis or the left coordinates
  • var dtworking with the y axis or the top coordinates

Lets add a console.log to see what these values are before we do the math. Add the following code to see what our variables and math are doing:

console.log("The value of dt is "+dt+" and is equal to "+ui.position.top+" - "+offset.top);
console.log("The value of dl is "+dl+" and is equal to "+ui.position.left+" - "+offset.left);
console.log("The value of ui.position.top is "+ui.position.top);
console.log("The value of ui.position.left is "+ui.position.left);
console.log("The value of offset.left is "+offset.top);
console.log("The value of offset.left is "+offset.left);

When you run the code the console.log() outputs the following:

The value of dt is 37 and is equal to 237 - 200
The value of dl is 152 and is equal to 352 - 200
The value of ui.position.top is 237
The value of ui.position.left is 352
The value of offset.top is 200
The value of offset.left is 200

Notice what the code is printing out, it is taking the ui.position.top and subtracting the value of offset.top and giving us the difference to equal variable dt. We do this math so we can update the top and left CSS properties in the next section of code, if we didn’t do this math, we would select and drag our elements and they would move sporadically on the page.

Next we are going to cover the other each function that loops through each of the selected elements expect $(“this”):

// take all the elements that are selected expect $("this"), which is the element being dragged and loop through each.
selected.not(this).each(function() {
     // create the variable for we don't need to keep calling $("this")
     // el = current element we are on
     // off = what position was this element at when it was selected, before drag
     var el = $(this), off = el.data("offset");
     el.css({top: off.top + dt, left: off.left + dl});

So we have the last big piece of code to make this script work. Like I said, you have the each function that runs through each element expect $(“this”), then we create two variables:

  • elwhich is the current element we are on
  • offwhich is the position of the elements when they were selected, before any type of movement and drag

The last segment: we are going to be adding or subtracting (we will subtract if the dt or dl is negative). The dl stands for delta left and dt stands for delta top. For instance lets set something up:

The current element we are on start at the coordinates: 10, 30, now we drag that to: 8, 15. Now lets run the math, the new position of the element is: 2, 15. Say, you drag it again, it runs the loop once again, and the off will be 2, 15 and the new value will be wherever the new coordinates are subtract the total delta from when the drag started until now, not just the last mouse movement.

Now that we did the math and we have captured the new value, update it is the css property and plug in the top and left coordinates.

So what did you think of it? Pretty interesting effect when you combine both of those UI elements to create select and drag. Share your thoughts and make sure to bookmark using the button below. Any improvements? Contact me.