Robot Has No Heart

Xavier Shay blogs here

A robot that does not have a heart

Ultimate NYTimes jQuery Slidebox

The New York Times has a pretty fancy box that slides out when you hit the bottom of an article. It draws attention without being too distracting. Very nice. Here’s how you can do it yourself with all the trendiest bells and whistles, CSS animation (with backup jQuery for crippled browsers), and google analytics tracking. See it in the wild over at my other blog TwoShay, or jump straight to the demo to grab the code.

To start with, some basic skeleton code. I’m using new HTML5 selectors, you can just use divs if you’re not that cool.

1
2
3
4
5
6
7
8
9
10
11
<section id='slidebox'>
  <a name='close'></a>
  <h1>Related Reading</h1>
  <div class='related'>
    <h2>Sense and Sensibility</h2>
    <p class='desc'>
      Another book by Jane Austen you will enjoy
      <a href='#' rel='related' class='more'>Read »</a> 
    </p>
  </div>
</section>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* Just the important styles - see the demo source for a fuller account */
#slidebox {
  position:fixed;
  width:400px;
  right: -430px;
  bottom:20px;

  -webkit-transition: right 100ms linear;
}

#slidebox.open { 
  right: 0px; 
  -webkit-transition: right 300ms linear;
}

This sets up an absolutely positioned box, hidden off to the right of screen. Adding a class of open to the box using jQuery will trigger a 300ms CSS animation to slide the box in, nice and smooth. The correct time to do this is when the user scrolls to the last bit of content on the page. What this content is will be dependent on your site, but whatever it is flag it with an id of #last. The following javascript is all we need:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
(function ($) {
  /* Add a function to jQuery to slidebox any elements */
  jQuery.fn.slidebox = function() {
    var slidebox = this;
    var originalPosition = slidebox.css('right');
    var boxAnimations = {
      open:  function() { slidebox.addClass('open'); },
      close: function() { slidebox.removeClass('open'); },
    }

    $(window).scroll(function() {
      var distanceTop = $('#last').offset().top - $(window).height();

      if ($(window).scrollTop() > distanceTop) {
        boxAnimations.open();
      } else {
        boxAnimations.close();
      }
    });
  }

  $(function() { /* onload */
    $('#slidebox').slidebox();
  });
});

That’s it! Everything from here on is gravy.

To deal with browsers that don’t support CSS animations yet, provide a fallback that uses jQuery animation using Modernizr to detect the browser’s capabilities:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
/* replacing the boxAnimations definition above */
var boxAnimations;
if (Modernizr.cssanimations) {
  boxAnimations = {
    open:  function() { slidebox.addClass('open'); },
    close: function() { slidebox.removeClass('open'); },
  }
} else {
  boxAnimations = {
    open: function() {
      slidebox.animate({
        'right': '0px'
      }, 300);
    },
    close: function() {
      slidebox.stop(true).animate({
        'right': originalPosition
      }, 100);
    }
  }
}

A close button is polite, allowing the user to dismiss the slidebox if they are not interested:

1
2
3
slidebox.find('.close').click(function() {
  $(this).parent().remove();
});

And finally, no point adding all this shiny without knowing whether people are using it! Google analytics allows us to track custom javascript events, which is a perfect tool for gaining an insight into how the slidebox is performing. It’s easy to use: simply push a _trackEvent method call to the _gaq variable (defined in the analytics snippet you copy and paste into your layout) and google takes care of the rest. Observe the full javascript code, with tracking added:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
(function ($) {
  jQuery.fn.slidebox = function() {
    var slidebox = this;
    var originalPosition = slidebox.css('right');
    var open = false;

    /* GA tracking */
    var track = function(label) {
      return _gaq.push(['_trackEvent', 'Slidebox', label]);
    }

    var boxAnimations;
    if (Modernizr.cssanimations) {
      boxAnimations = {
        open:  function() { slidebox.addClass('open'); },
        close: function() { slidebox.removeClass('open'); },
      }
    } else {
      boxAnimations = {
        open: function() {
          slidebox.animate({
            'right': '0px'
          }, 300);
        },
        close: function() {
          slidebox.stop(true).animate({
            'right': originalPosition
          }, 100);
        }
      }
    }

    $(window).scroll(function() {
      var distanceTop = $('#last').offset().top - $(window).height();

      if ($(window).scrollTop() > distanceTop) {
        /* Extra protection necessary so we don't send multiple open events to GA */
        if (!open) {
          open = true;
          boxAnimations.open();
          track("Open");
        }
      } else {
        open = false;
        boxAnimations.close();
      }
    });

    slidebox.find('.close').click(function() {
      $(this).parent().remove();
      track("Close");
    });
    slidebox.find('.related a').click(function() {
      track("Read More");
    });
  }

  $(function() {
    $('#slidebox').slidebox();
  });
})(jQuery);

/* Google analytics code provides this variable */
var _gaq = _gaq || [];

Tasty. For the entire code and complete styles, see the demo page.

Kudos to http://tympanus.net for getting the ball rolling.

inject and collect with jQuery

You know, I would have thought someone had already made an enumerable plugin for jQuery. Maybe someone has. Mine is better.

  • Complete coverage with screw-unit
  • Interface so consistent with jQuery you’ll think it was core
1
2
3
4
squares = $([1,2,3]).collect(function () {
  return this * this;
});
squares // => [1, 4, 9]

It’s on github. It deliberately doesn’t have the kitchen sink – fork and add methods you need, there’s enough code it should be obvious the correct way to do it.

As an aside, it’s really hard to spec these methods concisely. I consulted the rubyspec project and it turns out they had trouble as well, check out this all encompassing spec for inject: “Enumerable#inject: inject with argument takes a block with an accumulator (with argument as initial value) and the current element. Value of block becomes new accumulator”. Bit of a mouthful eh.

Post your improvements in the comments.

Unobtrusive live comment preview with jQuery

Live preview is shiny. First get your self a URL that renders a comment. In rails maybe something like the following.

1
2
3
4
5
6
7
8
9
def new
  @comment = Comment.build_for_preview(params[:comment])

  respond_to do |format|
    format.js do
      render :partial => 'comment.html.erb'
    end
  end
end

Now you should have a form or div with an ID something like “new_comment”. Just drop in the following JS (you may need to customize the submit_url).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
$(function() { // onload
  var comment_form = $('#new_comment')
  var input_elements = comment_form.find(':text, textarea')
  var submit_url = '/comments/new'  
  
  var fetch_comment_preview = function() {
    jQuery.ajax({
      data: comment_form.serialize(),
      url:  submit_url,
      timeout: 2000,
      error: function() {
        console.log("Failed to submit");
      },
      success: function(r) { 
        if ($('#comment-preview').length == 0) {
          comment_form.after('<h2>Your comment will look like this:</h2><div id="comment-preview"></div>')
        }
        $('#comment-preview').html(r)
      }
    })
  }

  input_elements.keyup(function () {
    fetch_comment_preview.only_every(1000);
  })
  if (input_elements.any(function() { return $(this).val().length > 0 }))
    fetch_comment_preview();
})

The only_every function is they key to this piece – it ensures that an AJAX request will be sent at most only once a second so you don’t overload your server or your client’s connection.

Obviously you’ll need jQuery, less obviously you’ll also need these support functions

1
2
3
4
5
6
7
8
9
10
11
12
13
// Based on http://www.germanforblack.com/javascript-sleeping-keypress-delays-and-bashing-bad-articles
Function.prototype.only_every = function (millisecond_delay) {
  if (!window.only_every_func)
  {
    var function_object = this;
    window.only_every_func = setTimeout(function() { function_object(); window.only_every_func = null}, millisecond_delay);
   }
};

// jQuery extensions
jQuery.prototype.any = function(callback) { 
  return (this.filter(callback).length > 0)
}

Viola, now you’re shimmering in awesomeness.
Demo up soon, but it’s similar to what you see on this blog (though this blog is done with inline prototype).

A pretty flower Another pretty flower