Pull to Refresh

Pull to refresh is a common design pattern amongst major mobile apps. Facebook, twitter, gmail, etc all use a “pull to refresh” technique. In my previous post on the new Quick Return design pattern, I discussed a way to implement this in a desktop environment. Now, I present to you, how to implement the “Pull to Refresh” design pattern on the desktop:

Demo

Usage:

Simply download the JS source or copy/paste the JS source below and include it in your markup.

A global, called Refreshable, becomes available once the script is included. To use, you can call its initialize(), which takes in 2 options as an object{}:

  1. refreshAction
  2. refreshContainer

refreshAction must be a function. It is the action you want to bind to the refresh event triggered on the refreshContainer.

refreshContainer needs to be addressed by an ID. The script, at this time, doesn’t support an array of elements.

So, in the source below you’ll see where I initialized it saying:

Refreshable.initialize({
refreshAction: function() {
$.getJSON("http://date.jsontest.com/", function(data) {
$("#container p").html("Today is " + data.date + " and it is " + data.time);
});
},
refreshContainer: "#container"
});

I’m passing in a function that goes and fetches the current date and time from a provider, then updates the container w/ this information.

HTML:

<div id="container" class="container">
<p>Pull my bottom</p>
</div>

CSS:

.container { 
width: 350px;
height: 350px;
padding: 5px;
margin: 5px;
background: #ccc;
position: relative;
border-bottom-right-radius: 10px;
}

JS:

var Refreshable = (function () {
var refreshAction;
var refreshContainer;
var $refreshContainer;
var refreshContainerHeight;
var refreshElString;
var $refreshEl;
var offset;
var offsetDiff; startHover = function (evt) {
$(this).css("background-color", "rgba(0,0,0,0.5)");
}
stopHover = function (evt) {
$(this).css("background-color", "transparent");
}
allowResize = function (evt) {
evt.preventDefault();
$refreshContainer.addClass("resizable");
offset = evt.pageY;
}
stopResize = function (evt) {
$refreshContainer.removeClass("resizable");
$refreshContainer.animate({
height: refreshContainerHeight
});
offset = 0;
}
resize = function (evt) {
if ($refreshContainer.hasClass("resizable")) {
offsetDiff = evt.pageY - offset;
if (offsetDiff > 0) {
$refreshContainer.innerHeight(refreshContainerHeight + offsetDiff);
}
if (offsetDiff > refreshContainerHeight * 0.25) {
$refreshContainer.trigger("refresh");
}
}
}
var refreshIt = function () {
stopResize();
refreshAction();
} return {
initialize: function (options) {
refreshAction = options.refreshAction;
refreshContainer = options.refreshContainer;
$refreshContainer = $(options.refreshContainer);
refreshContainerHeight = $(refreshContainer).innerHeight();
refreshElString = '<div class="refreshEl" style="position:absolute; width: 100%; height: 45px; bottom: 0; left: 0; cursor: s-resize; outline: 50px transparent solid; z-index: 999999; border-bottom-right-radius: 10px;"></div>';
$refreshContainer.append(refreshElString);
$refreshEl = $refreshContainer.children(".refreshEl").first();

this.eventRegister();
return this;
}, eventRegister: function () {
$refreshContainer.on("refresh", refreshIt);
$refreshEl.on("mousedown", allowResize)
.on("mouseup", stopResize)
.on("mousemove", resize)
.on("mouseleave", stopHover)
.on("mouseover", startHover); }
}; })();
//Code you saw before Refreshable.initialize({
refreshAction: function() {
$.getJSON("http://date.jsontest.com/", function(data) {
$("#container p").html("Today is " + data.date + " and it is " + data.time);
});
},
refreshContainer: "#container"
});

I wanted to keep the CSS down to a minimum for portability. The CSS included is simply for the container to serve as a demo, it doesn’t have to be followed strictly.

The only requirement of the CSS is that it needs to be positioned relatively. Otherwise, the refresh element appended to the bottom will not seat inside the container.

That’s all I have for now. As with my other posts, I’ll be making edits to make the code better, more extendable, etc.

Thanks for reading.

 

Actually Vertically-Aligned CSS (no javascript necessary, horizontally aligned bonus!)

.vertical-align-container { height: 100%; position: absolute; top: 0; right: 0; bottom: 0; left: 0; text-align: center; }
.vertical-align-container::after { content: ''; display: inline-block; height: 100%; margin-right: -0.25em; vertical-align: middle; }
.vertical-align-container > .vertical-align-content { display: inline-block; vertical-align: middle; }

That’s it. That’s the magic secret.

For those of you that just want to c/p to see it for yourselves:
<html>
<head>
<style>
.vertical-align-container { height: 100%; position: absolute; top: 0; right: 0; bottom: 0; left: 0; text-align: center; }
.vertical-align-container::after { content: ''; display: inline-block; height: 100%; margin-right: -0.25em; vertical-align: middle; }
.vertical-align-container > .vertical-align-content { display: inline-block; vertical-align: middle; }
</style>
</head>
<body>
<div class="vertical-align-container">
<div class="vertical-align-content">
Here is something vertically aligned
</div>
</div>
</body>
</html>

I hope you find this helpful. If you do -

Follow me on twitter @william_beard

Implementing Quick Return Design Pattern on the Web

Android’s Google Now seems to have brought a new UI design pattern to mobile devices.

I found this to be a very cool feature and a very cool, applicable design pattern for the web. Most of the time, when reading a long document, sites or applications provide a “Back to Top” button to jump back up to the top of the document in lieu of providing menu options fixed to the page at all times. This is a great way for reserving as much real estate as possible for the content.

However, there may be that off chance a user wants to continue viewing the content, or stay within the proximity of the content they are currently viewing. Scrolling up is a great indicator that they’re looking to reach some sort of functionality at the top of the screen. This has cued me to start on making a Quick Return javascript plugin for the web. It’s actually very simple:

/**** Non-jquery ****/
var positionArray = new Array();
positionArray.push(window.scrollY);
if (positionArray.length > 10) {
 var previousPosition = positionArray.shift();
}
if (window.scrollY < previousPosition) {
 domElement.className += " qr";
}
else {
 domElement.className = domElement.className.replace( /(?:^|\s)qr(?!\S)/g , '' );
}
/**** jquery ****/
var positionArray = new Array();
positionArray.push($(window).scrollTop);
if (positionArray.length > 10) {
 var previousPosition = positionArray.shift();
}
if ($(window).scrollTop < previousPosition) {
 $(domElement).addClass("qr");
}
else {
 $(domElement).removeClass("qr");
}

Beginning of the document:

1

This is at the top of the document. Then you scroll down and the top menu, as usual, stays in its place.

2

Then, when you begin to scroll up the document, the top navigation appears:

3

In this particular case, the user will be viewing an API document. This design pattern, like others, will not be one-size-fits-all. It may work for you, it may not.

I’ll be adding some code to “soften” the correlation of scrolling up and showing the returned container. Any suggestions or thoughts?


			

Sanitize Backbone.js Models to prevent XSS

This isn’t groundbreaking code, but you may find it useful to know how to take a step to prevent XSS attacks when implementing Backbone MV*. Some JavaScript frameworks automatically escape or sanitize the values being passed to the model. Backbone does not. However, the library it’s built on (Underscore.js) does provide an easy way to escape values.

First, in your Model, create your initialize() method, and in it, use the _.each method to iterate over the attributes object, passing the value to a method belonging to the Model named “sanitize”.

var CartItem = Backbone.Model.extend({
  initialize: function() {
    _.each(this.attributes, function (val, key)
      this.set(key, this.sanitize(val));
    }, this);
  }
});

Let’s add our sanitize() method. In this method, simply take in the string as a parameter, and return the escaped version of it, using Underscore’s _.escape method.

var CartItem = Backbone.Model.extend({
  initialize: function() {
    _.each(this.attributes, function (val, key) {
      this.set(key, this.sanitize(val));
    }, this);
  },
  sanitize: function (str) { 
    return _.escape(str) 
  } 

});

I recommend sanitizing in your model’s initializer so that you ensure it’s properly scrubbed before calling Model.save() and sending nasty XSS or SQL injection to your server. Also, sanitize anywhere you update the model or allow edits to the model.

I hope you found this post useful. If you have anything to add or find any problems, let me know.

formValidator.js – Simple jQuery form validation plugin

Made my first jQuery plugin for validating forms on the front-end, before submit. It has some options as well to make it more flexible for your needs.

To use the plugin, please download the source from my github repo: https://github.com/wbeard/formvalidator

I plan on adding more to it. Here are some things to cover:

To Use:

import jQuery 1.72 js file

import validate.js file

link validate.css file

attach to desired form (e.g. $(“selector”).formValidator();

can take options such as background & color for customization (e.g. $(“selector”).formValidator({ “background”: “red”, “color”: “white” });

when you define a dom element add the appropriate classes for validation to happen on change or keyup, whichever is defined in the plugin

Classes:

required – defines required input

numeric – requires numeric input

phone – masks text with (###) ###-####

date – masks text with date mm/20yy

card – accepts only 3,4,5, or 6 as valid first character and determines appropriate max length of cvv input box and itself

email – simple regex expression being checked against

Options:

background – Sring value. Background of tooltip, default is transparent

color – String value. Font color of tooltip, default is red

orientation – String value.  Position of tooltip. Valid options are right, top, left, or bottom. Default is right.

disableSubmit – Boolean. Determines whether submit button associated with selected form should be disabled until all fields are valid. Default is true.

excludedList – If there are other buttons being selected and you would like to explicitly not select them, pass them in an array,  with a jQuery selector, e.g. $(“.selector”)

Feel free to check out the source or fork at https://github.com/wbeard/formvalidator/

I’ll be making this more scalable and easy to use. Its been made more specifically for an .aspx page for collecting payments, so some of its quirks were caused by the quirks of creating jQuery for aspx & .net. I’ll be making a more generic approach and will update accordingly.

Thanks!

Putting Together the Petals: A Chronological Analysis of “A Rose for Emily”

I’ve been getting a ton of traffic on this post recently. Please leave comments if you have any questions or found it hard to read in this format on WordPress. I’d like to learn a little more about why you’re reading it. Doing a term paper? Just a fan of William Faulkner?

As the sleepy reader saunters through the meadow of Faulkner’s A Rose for Emily, he may make his way through its many different paths. Most power-walk their way on a straight path, the most efficient and timely. They see the Old South juxtaposed to the New, the dilapidated cotton gins absorbed by gas stations, the antiquated mansions and Emily Grierson, the loner; all the fundamentals of a Southern Gothic. Others take the long road and discover the forest is scattered, telling its story with convoluted minutia easy to trip over and not easy to see. Faulkner, in his true style, has written a story in a way never thought possible of a literary scholar, mathematically. What are the motives in making the recollection of time scattered about like leaves on a lawn? From an author’s point of view, it could be to confuse the reader and persuade him to criticize the text more and more until the puzzle is solved. Thinking as a narrator, it could be to obscure the events into a story more convenient for their purposes. The possibilities of both the intentions and the methods are endless. To me, the author and the narrator come to a point of agreement as to what the intention of the story is when speaking of the confederate soldiers at Emily’s wake. The soldiers were said to recall the times that “…they had danced with her and courted her perhaps, confusing time with its mathematical progression, as the old do, to whom all the past is not a diminishing road but, instead, a huge meadow which no winter ever quite touches…” (Faulkner 34). I believe Faulkner, ultimately, demonstrates that a memorable artifact has been lost and it will soon be forgotten by a progressing society.

Continue reading