Posts Tagged 'Exercise'

February 14, 2013

Tips and Tricks – Building a jQuery Plugin (Part 2)

jQuery plugins don't have to be complicated to create. If you've stumbled upon this blog in pursuit of a guide to show you how to make a jQuery plugin, you might not believe me ... It seems like there's a chasm between the "haves" of jQuery plugin developers and the "have nots" of future jQuery developers, and there aren't very many bridges to get from one side to the other. In Part 1 of our "Building a jQuery Plugin" series, we broke down how to build the basic structure of a plugin, and in this installment, we'll be adding some usable functionality to our plugin.

Let's start with the jQuery code block we created in Part 1:

(function($) {
    $.fn.slPlugin = function(options) {
            var defaults = {
                myVar: "This is", // this will be the default value of this var
                anotherVar: "our awesome",
                coolVar: "plugin!",
            };
            var options = $.extend(defaults, options);
            this.each(function() {
                ourString = myVar + " " + anotherVar + " " + coolVar;
            });
            return ourString;
    };
}) (jQuery);

We want our plugin to do a little more than return, "This is our awesome plugin!" so let's come up with some functionality to build. For this exercise, let's create a simple plugin that allows truncates a blob of text to a specified length while providing the user an option show/hide the rest of the text. Since the most common character length limitation on the Internet these days is Twitter's 140 characters, we'll use that mark in our example.

Taking what we know about the basic jQuery plugin structure, let's create the foundation for our new plugin — slPlugin2:

(function($) {
    $.fn.slPlugin2 = function(options) {
 
        var defaults = {
            length: 140,
            moreLink: "read more",
            lessLink: "collapse",
            trailingText: "..."
        };
 
        var options = $.extend(defaults, options);
    };
})(jQuery);

As you can see, we've established four default variables:

  • length: The length of the paragraph we want before we truncate the rest.
  • moreLength: What we append to the paragraph when it is truncated. This will be the link the user clicks to expand the rest of the text.
  • lessLink: What we append to the paragraph when it is expanded. This will be the link the user clicks to collapse the rest of the text.
  • trailingText: The typical ellipses to append to the truncation.

In our jQuery plugin example from Part 1, we started our function with this.each(function() {, and for this example, we're going to add a return for this to maintain chainability. By doing so, we're able to manipulate the segment with methods. For example, if we started our function with this.each(function() {, we'd call it with this line:

$('#ourParagraph').slPlugin2();

If we start the function with return this.each(function() {, we have the freedom to add further manipulation:

$('#ourParagraph').slPlugin2().bind();

With such a simple change, we're able to add method calls to make one massive dynamic function.

Let's flesh out the actual function a little more. We'll add a substantial bit of code in this step, but you should be able to follow along with the changes via the comments:

(function($) {
    $.fn.slPlugin2 = function(options) {
 
        var defaults = {
            length: 140, 
            moreLink: "read more",
            lessLink: "collapse",
            trailingText: "..."
        };
 
        var options = $.extend(defaults, options);
 
        // return this keyword for chainability
        return this.each(function() {
            var ourText = $(this);  // the element we want to manipulate
            var ourHtml = ourText.html(); //get the contents of ourText!
            // let's check if the contents are longer than we want
            if (ourHtml.length > options.length) {
                var truncSpot = ourHtml.indexOf(' ', options.length); // the location of the first space (so we don't truncate mid-word) where we will end our truncation.
 
   // make sure to ignore the first space IF the text starts with a space
   if (truncSpot != -1){
       // the part of the text that will not be truncated, starting from the beginning
       var firstText = ourHtml.substring(0, truncSpot);
 
       // the part of the text that will be truncated, minus the trailing space
       var secondText = ourHtml.substring(truncSpot, ourHtml.legnth -1);
                }
            }
        })
    };
})(jQuery);

Are you still with us? I know it seems like a lot to take in, but each piece is very straightforward. The firstText is the chunk of text that will be shown: The first 140 characters (or whatever length you define). The secondText is what will be truncated. We have two blobs of text, and now we need to make them work together:

(function($) {
    $.fn.slPlugin2 = function(options) {
 
        var defaults = {
            length: 140, 
            moreLink: "read more",
            lessLink: "read less",
            trailingText: "..."
        };
 
        var options = $.extend(defaults, options);
 
        // return this keyword for chainability
        return this.each(function() {
            var ourText = $(this);  // the element we want to manipulate
            var ourHtml = ourText.html(); //get the contents of ourText!
            // let's check if the contents are longer than we want
            if (ourHtml.length > options.length) {
                var truncSpot = ourHtml.indexOf(' ', options.length); // the location of the first space (so we don't truncate mid-word) where we will end our truncation.
 
   // make sure to ignore the first space IF the text starts with a space
   if (truncSpot != -1){
       // the part of the text that will not be truncated, starting from the beginning
       var firstText = ourHtml.substring(0, truncSpot);
 
       // the part of the text that will be truncated, minus the trailing space
       var secondText = ourHtml.substring(truncSpot, ourHtml.legnth -1);
 
       // perform our truncation on our container ourText, which is technically more of a "rewrite" of our paragraph, to our liking so we can modify how we please. It's basically saying: display the first blob then add our trailing text, then add our truncated part wrapped in span tags (to further modify)
       ourText.html(firstText + options.trailingText + '<span class="slPlugin2">' + secondText + '</span>');
 
       // but wait! The secondText isn't supposed to show until the user clicks "read more", right? Right! Hide it using the span tags we wrapped it in above.
       ourText.find('.slPlugin2').css("display", "none");
                }
            }
        })
    };
})(jQuery);

Our function now truncates text to the specified length, and we can call it from our page simply:

<script src="jquery.min.js"></script>
<script src="jquery.slPlugin2.js"></script>
<script type="text/javascript">
$(document).ready(function() {  
    $('#slText').slPlugin2();  
});
</script>

Out of all the ways to truncate text via jQuery, this has to be my favorite. It's feature-rich while still being fairly easy to understand. As you might have noticed, we haven't touched on the "read more" and "read less" links or the expanding/collapsing animations yet, but we'll be covering those in Part 3 of this series. Between now and when Part 3 is published, I challenge you to think up how you'd add those features to this plugin as homework.

-Cassandra

December 24, 2012

Giving From (and For) the Heart

This time of year is often referred to as "The Season of Giving," and we thought we'd share two SLayers' stories about their involvement in the American Heart Association Heart Walk. Like last year, we split up into fundraising teams for the AHA with a goal of raising $100,000. In addition to those fundraising efforts, SoftLayer also encouraged employees to get active and get involved in the annual Heart Walks in Houston and Dallas. Here's our on-location coverage from two team captains who attended those events this year:

Dallas

My name is Fabrienne Curtis, and I work in the Accounting Department at SoftLayer. I joined a team with thirty other people (from several different departments) to raise money for the American Heart Association, and because I love to help and work on community projects, I volunteered to be a team captain. Our team had a ton of great ideas for fundraisers, so we set an ambitious goal of raising $12,400 ($400 per person). When the dust settled, I'm proud to report that we me that goal with a total team tally of $12,488 (which SoftLayer then matched).

Beyond the fundraising, participating in the Dallas Heart Walk at Victory Park was a highlight this year. No one on my team knew that this walk had a personal meaning to me ... I lost my dad to congestive heart failure and wanted to walk in his behalf. When I got to the Heart Walk, I was touched. There was a "Survivor Wall" and there were several signs where you could share who you're walking on behalf of. If not for SoftLayer, I probably wouldn't have participated in the Heart Walk, so as I wrote on the wall and created a sign for my dad, I thought about how good it felt to work for a company that truly cares about the well-being of its employees.

SoftLayer Photo Booth

SoftLayer added a little flair to the event by setting up a photo booth for people to take pictures and take home, and with the help of Don Hunter, Hao Ho and my husband Jerry, 679 photos were taken!

SoftLayer Photo Booth

Here are some pictures I snapped from the 2012 Dallas Heart Walk:

SoftLayer Heart Walk
The Start!
SoftLayer Heart Walk
The SoftLayer "Uniform"
SoftLayer Heart Walk
The Crowd
SoftLayer Heart Walk
Victorious!

Thank you SoftLayer for having a heart! If you want more coverage of this years event, check out this Dallas Heart Walk 2012 video and click through to our Dallas Heart Walk Flickr album.

-Fabrienne

Houston

Dallas didn't get to have all of the fun when it comes to the AHA Heart Walk, and I made sure to document the Houston goings-on to share with our avid SoftLayer Blog readers. From bake sales to ice cream socials, the Houston office was diligent about donating money and raising heart-health awareness for months prior to the 2012 walk, and those months were extremely eventful. Like Fabrienne, I jumped at the opportunity to be one of 18 team captains at SoftLayer, and considering the fact that cardiovascular disease is the number one killer of Americans, I was inspired to get everyone involved.

I'll be the first to admit that I am not in the best of shape, so a five-kilometer walk through a course at Reliant Stadium would be pretty challenging. My team had been tirelessly preparing for the 5k "mini-marathon" walk, and as November approached, you could sense the excitement and enthusiasm brewing. Walking only one mile can add up to two hours to your lifespan, so in the process of preparing for the walk, we added quite a few hours to our collective lives. When the big day finally arrived, we were ready:

SoftLayer Heart Walk
The Houston Heart Walk SLayers

Given that our day started at an unbelievable 7:00am on a Saturday, most of our participants were tired-eyed and ready to chow down on the free burritos and fruit provided by SoftLayer, and by the time we fired up the photo booth and broke out the goofy props, everyone was wide awake. It's like they say, "Give a man a fish and he'll eat for a day ... Give a man fun props and a camera, and he'll have a blast (and pictures that can be used against him." Actually, I don't know if "they" say that, but it's true:

SoftLayer Heart Walk

Before we knew it, a gunshot of glitter and colorful confetti got the crowd of people moving down the 3.1-ish mile track, and we were hooting and cheering, pumped to represent our company! By mile two, my legs were a little wobbly and the sun was scorching, I could see that our dog, Rikku (whom had been carried the entire way) looked was confused about why I was putting her through the exhausting task of being comfortably in my arms as we herded through the people like cattle.

SoftLayer Heart Walk

AHA water stations and mile markers reminded us that we were doing it for the best cause ever: The people we love and the people of the past that have been lost due to heart disease. It's a safe bet that if you don't know someone directly affected by heart disease, you will eventually. The American Heart Association organizes these fundraisers and walks every year across the world to gather donations and raise awareness so that one day, we may be able to conquer this silent killer. With their donations, they're able to participate in research for preventative treatment, provide education to children to avoid obesity and fund medical research that could one day breakthrough and save lives.

All in all it was a wonderful experience, one that I'll definitely be sure to be a part of next year.

-Cassandra

SoftLayer Heart Walk

Categories: 
June 16, 2011

An Exercise in Innovation

Some of the best ideas come from people who think "outside of the box." SoftLayer was born in a living room six years ago when we decided to look at the staid hosting industry from a new perspective. We said, "We don't want to build a company to meet customers' current needs. We want to build a company to meet the needs our customers don't even know they have yet," and that's one of the biggest reasons the SoftLayer platform has IPv6, KVM over IP, private network, out-of-band management and standardized pod-based data centers.

Only people with a certain level of "crazy" can recognize opportunities for innovation, and because SoftLayer's motto is "Innovate or Die," to incubate innovation, we have to create an environment that enables employees to take their "crazy" and run with it. Speaking of "crazy," meet Phil.

Phil plays guitar, tests software in non-standard ways, and has a bobble-head of himself. Some would say he marches to the beat of a different drummer – a drummer that may or may not be overdosing on caffeine.

Phil was tasked with a 12-week project: If SoftLayer is built for what our customers are going to need tomorrow, figure out what customers will need after "tomorrow." He'd have access to people and resources up and down the organization to build his idea, and the experiment is set up to incubate his innovation:

  1. Because there are no bad ideas in brainstorming, anyone helping Phil should do so without questioning the logic or "sanity" of what he asking for help with.
  2. Phil can spend up to 20% of his work hours building his idea.
  3. Anyone who helps Phil can spend up to 10% of his/her work hours to build his idea.
  4. Phil can have space in H2 to build his idea.
  5. Regardless of apparent success or failure, the project will conclude at the end of 12 weeks. From there, we'll evaluate the "good" and "not as good" ideas from the experiment.

It'd be impossible to guarantee the success of any kind of project like this because it's a little like catching lightning in a bottle, but I was interested to see what kinds of operational changes he came up with over the course of the three months. We might see the evolution of the next brilliant idea in hosting, or we'd see a lot of hilariously terrible ideas.

Then I saw his first installment:

By the time I got to "circumstantiate," I had the phone in my hand to call off the project. What I didn't expect was Phil's tearful pleading to take the idea down a different path. They say you don't get a second chance to make a first impression, and despite the fact that this first impression was pretty awful, I decided to give him another shot (with a much more limited scope):

  1. Apparently there are bad ideas in brainstorming, but anyone who helps Phil on his "new path" should try to be supportive.
  2. Phil can spend up to 5% of his work hours building his idea.
  3. Phil can't take anyone else from SoftLayer away from their jobs during work hours.
  4. Phil can have space in the Houston office to build his idea.
  5. The project is scheduled to run for 12 weeks. There's no guarantee that it'll make it through next week.

If you have ideas for Phil, feel free to contribute. He'd probably appreciate the help.

-@lavosby

Subscribe to exercise