Category Archives: jQuery

#OneSpark #EdSpark #YearOfAwesome #lolhashtags

So, since I’m not busy enough these days I decided to help out my friend Courtney with a project of hers she wanted to enter into OneSpark. If you’re not familiar with OneSpark, it’s a crowdfunding festival in Jacksonville that helps get innovation and investors in the same place, to help local projects get funded. That’s the idea at least, but in practice it’s more like an idea some rich bohemians came up with to get people to remember that downtown Jacksonville exists, while simultaneously not really managing to get anybody’s projects off the ground.

Alas, I promised myself this would not turn into a rant. 🙂

The idea we entered is a nifty one. It is an ABA Therapy App (in fact, that’s the name) that allows behavior analysts and therapists to work more efficiently with autistic children. Right now it supports manding, assorted flashcards, and analytics, but we want to do all sorts of useful things with the app. The prototype is currently written in jQuery Mobile, but it may be rewritten natively for the final version. All in all it is a pretty exciting project and we got a lot of great feedback. We also got some wonderful funding and met some great allies in our cause.

screenshot-numbers

This was all born out of a pact we all made called the “Year of Awesome.” I know that sounds like some kind of Honda used car sales event, but really all it is, is the promise that we’re going to have our twenties go out with a bang instead of a whimper. You know, get the ball rolling on stuff that should have been rolling years ago, like starting a business and building cool ideas. So this was a way to do just that, and I think we succeeded. Maybe we didn’t win prizes or anything, but we built something, attracted the investors we needed, and got a nice booth at EdSpark. And hey, we got more funding than most. Now there are some next steps to take care of, and you’ll soon be seeing some exciting new mobile projects from me.

The Year of Awesome is go.

Fantasy Healthcare

I have an announcement to make: I placed 3rd in the Robert Wood Johnson foundation’s Games to Generate Data Challenge. I have been secretly working on this project for most of the year, and now that it’s over, I can talk about what I’ve been building.

Fantasy Healthcare is a game that allows friends (in the Wisconsin area for this version) to create their own healthcare provider dream team and pit it against other friends and players online. The provider data and provider names are 100% real, but the doctor/department names have been changed to protect the innocent. The idea is that players will better familiarize themselves with providers in the area, while also learning which providers perform best in certain areas.

The interesting part of all this is how it all got started. At my public sector job, I joined up with a group that was looking to enter the Games to Generate Data Challenge as a team, but alas, government red tape (and lawyers) prevented this from happening. However, since I was a contractor, I was able to take an idea of my own into the challenge and see how far it would get. It ended up being a good enough idea to place in the Top 5, so from there I developed the game on my own.

Fantasy Healthcare is written in HTML5, Canvas, CSS3, Javascript, jQuery, jQuery Mobile, PHP, and MySQL. The back end stuff runs on a Linux server. The Canvas stuff is also cross-compiled to native iOS and Android platforms for the efficiency and fast performance you expect from a game. I did it all myself, so considering I competed with some large teams and some big industry players, I guess I did pretty well for 3rd place.

So besides winning some nice prizes, I also got a trip to Boston to attend Games for Health, and a trip to the Health 2.0 Conference in San Jose to see the winner announcements. First off, Ben Sawyer’s Games for Health project in Boston was a wonderful experience, and I wish I were able to go again. There are really some amazing interactive ideas out there ready to transform the industry. As far as Health 2.0, I also had a great time hanging out in the Valley, drinking local brews and eating some In-N-Out Burger. The 1st and 2nd Place winners were totally deserving of their prizes, each having some fun-looking and interesting games, and I sincerely wish them all the best with their endeavors.

While I was in San Jose I got caught up in the government shutdown, but that’s a story for another time.

The Robert Wood Johnson Foundation and Health 2.0 are doing some wonderful things right now to provoke and promote bleeding edge ideas in the healthcare industry, so be sure to visit their challenge site.

What’s next for Fantasy Healthcare? I’d like to publish the apps and expand it to more cities. This will take some time I don’t have at the moment, though. In the meantime, it is available here for anyone to play with.

The New Way to do Event Bubbling

All Javascript developers should be familiar with event bubbling. For those of you who don’t know, event bubbling is when DOM events move up the chain from bottom to top. In other words, if you click on a <li>, the <body> will get clicked first, then the <ul>, then the <li>. In IE, of course, it does the exact opposite (“event capturing”), but with the advent of jQuery, this is pretty much a moot point.

So why is it important to know? Well, imagine you’ve attached a click event to an <li>. It may not be a problem now, but if your <ul> ends up with thousands of <li>s, you’ve got thousands of bindings in the DOM, which is going to be a performance killer among other things. Instead, simply attach the click event to the <ul>, then inside the event, figure out what <li> got clicked on and react accordingly.

By the way, this is an interview question for every Javascript-related job ever. Know what it is and why it’s important.

I was going to post a simple example on how to do this, but apparently this is entirely the point of jQuery’s new “on” method. I use “on” all the time, and you should too, and if you are still using “delegate” or the dreaded “live” to bind events dynamically, you should start using “on” instead. So anyway, here is how to use “on” to efficiently bubble events:

$('ul').on('click','li', function(evt){
alert("cream cheese");
});

What this code is doing is binding to the <ul>, but only firing the callback if a child <li> node was targeted. I’ve always used $(document).on as a force of habit, but really you should be using the parent of the object you want to bind to. Folks, it doesn’t get any simpler than this. Sure wish I understood this months ago….

Presenting my latest project, SoulTrade

As you might have guessed, I’ve been working on another app these past few weeks. This represents only 2 weeks of work, so overall I’m okay with how it turned out. Without further ado, I present:
SoulTrade (soultra.de)
(available for iOS and Android!)

What is SoulTrade? It’s a market for buying and selling souls, basically. Yeah I know, it’s a pretty stupid idea, but I mostly just wanted to flex my design and development muscles with some of my free time. I really didn’t care what the website did, as long as I got to use PHP/MySQL/jQuery/Javascript/HTML5/CSS3. So ironically, this project really has no soul, heh.

Technical details: SoulTrade was written by me in 2-3 weeks with a PHP/MySQL back end using my own framework. The front end was designed by me in Photoshop and Dreamweaver, and of course utilizes HTML5/CSS3/Javascript/jQuery. The website is running on a LAMP stack, while the mobile version is using jQuery Mobile and Phonegap.

Enjoy.

…mwahahaha….

Custom Accordion Snippet using jQuery

Whenever I’ve built my own accordion script in jQuery, it’s always had the same problem: when you click on the collapsible that’s already open, it closes itself, then immediately reopens. Looking for alternative accordion scripts, I’ve noticed everyone else’s seems to have the same problem, so I came up with a deliciously simple way to solve it.

First, a little background. The reason this is happening is completely logical and due to the synchronous nature of jQuery animation. The way most developers go about their accordions is to make sure all others are closed, then open the requested accordion. This method works great unless you want to be able to close an accordion. Without further ado, here’s the easy solution:

HTML:
<div>
<h2>First</h2>
<p>Content</p>
</div>
<div>
<h2>Second</h2>
<p>Content</p>
</div>

Javascript:
$(document).on('click', '.collapsible h2', function(evt){
$(this).addClass('clicked');
$('.collapsible h2:not(.clicked)').removeClass('selected').next().slideUp(500);
if($(this).hasClass('selected')){
$(this).removeClass('selected').next().slideUp(500);
} else {
$(this).addClass('selected').next().slideDown(500);
}
$('.collapsible h2').removeClass('clicked');
});

Easy, right? Embarrassingly so. But I didn’t see any good examples online, so here you are.

Update 4/10: Fixed a bug in the :not selection.

jQuery Image Slideshow

Ever wanted or needed to make a slideshow system like you see on news websites? Here is a simple HTML/CSS/jQuery template to help give you a jumpstart. Here are some of the features:

– JSON-based input
– will handle a mixture of horizontal and vertical images of any size
– image descriptions can contain HTML tags
– navigate slides using buttons or arrow keys
– view and jump to slides visually
– automatic advance button
– shows thumbnails when hovering over slide buttons
– responsive layout (for mobile and iframe widgets. Non CSS3-based so it works in IE7 and 8)
– tested in IE8, FF, Chrome, Opera
– lightweight and easy to modify

I started working on a fullscreen mode for it, but got frustrated with the spotty browser support. I hope to eventually come back to that feature… but at any rate, here it is in 1.0 form. You can use it in your projects, but if it’s commercial, be nice and put me in the credits.

(DOWNLOAD COMING SOON…)

SineBob.js: A Simple jQuery Plugin for Creating Easy Sine/Cosine Effects

Ever notice that, even with jQuery’s Easing plugin and CSS3 transforms, it’s not really easy to make sine effects in your frontend projects? Being a game designer, I’m a sucker for sine, so this has been bothering me for awhile. Sooo… I finally decided to do something about it. This is an extremely simple jQuery plugin that allows you to add bobbing effects (horizontal or vertical), sine fades, sine scaling, sine rotating, and rotoscaling. Example usage is as follows:

Default vertical bobbing effect:
$("div").sinebob();

More options:
$("div").sinebob({direction:”left”,offset:60,length:120,interval:10});

Alternate bobbing effect (a simpler implementation with better timing control but less accuracy):
$("div").sinebob({mode:”simple”,ticks:3});

Sine Fading:
$("div").sinebob({mode:”fade”});

Scaling:
$("div").sinebob({mode:"scale",offset:10,length:1});

Rotation:
$("div").sinebob({mode:"rotate",offset:0,length:10});

Rotoscaling (both rotation and scale):
$("div").sinebob({mode:"rotoscale",offset:2,length:10,s_offset:10, s_length:2});

NEW! Text sinewave scroller (beta):
$("div").sinebob({mode:"text",length:10,increment:0.1,speed:15});

I threw this together in a day, and it is my first attempt at a jQuery plugin, so go easy on me.

Downloads (COMING SOON):
jQuery.SineBob.js v1.1
jQuery.SineBob.js v1.1 (minified)

Creating a Hierarchical Dropdown List from JSON Data Using jQuery

Recently I ended up with a project requirement that needed to build dropdown menus from external data. Because the project ran offline, databases and backend programming were out of the question, so I had decided to use JSON as the storage medium for the package data as well as the manifest of all packages. The challenge would be both coming up with a JSON format for storing hierarchical data, and being able to parse it in Javascript. Here’s ultimately what I came up with:

External JSON file:
{
"name": "Example Package",
"author": "Chris Bartek",
"contents": [
{
"title": "Menu 1",
"href": "menu1.html",
"children": [
{
"title": "Submenu 1",
"href": "submenu1.html"
},
{
"title": "Submenu 2",
"href": "submenu2.html"
}]
},
{
"title": "Menu 2",
"href": "menu2.html",
"children": [
{
"title": "Submenu 1",
"href": "submenu1.html"
},
{
"title": "Submenu 2",
"href": "submenu2.html",
"children": [
{
"title": "Subsubmenu 1",
"href": "subsubmenu1.html"
}]
}
]
}
]
}

Javascript/jQuery:
$.getJSON('package.json', function(data){
var module = [];
$.each(data, function(key, val){
module[key] = val;
});

var ul = $('<ul id="nav"></ul>');
$.each(module.contents, function(key, value){
var func = (function (item, list){
if(item){
if(item.href && item.title){
$(list).append($('<li></li>', {
"html": $('<a></a>', {
"href": item.href,
"html": item.title
})
}));
}
if(item.children && item.children.length){
var sublist = $('<ul></ul>');
for(index in item.children){
func(item.children[index], sublist);
}
$(list).children().last().append($(sublist));
}
}
});
func(value, $(ul));
});
$('nav').html(ul);
});

All that’s left is to hook in a dropdown menu script. I used a pure CSS solution, but a jQuery one would work, too. Hope this helps someone out there.

Common Sense By Any Other Name…

Seems like these days everyone gets to give a brand name to common sense, obvious practices. OOCSS, for instance… using DRY principles with CSS, come on, that’s just good practice. SCRUM… “let’s have meetings to discuss what’s progressing and what has problems–nobody’s ever thought of that before!” And then silly ideas from ages past, like sIFR and Cufón, the ridiculous answers to problems that weren’t really that huge of problems… well, those weren’t really common sense, more like the opposite, really. Since people like Inman get their 15 minutes of fame for thinking they’re the only ones that ever thought of using Flash to embed fonts, perhaps it’s time I came up with the Bartek Web Design Philosophy. I’m gonna make this up as I go…

  1. Be as semantic as possible. Let everything be what it is, and the universe will stay in balance.
  2. Validate your HTML. If it doesn’t pass validation, and you don’t want to let go of the code that’s causing it, you should probably rethink it. If you truly love Chromeframe, you must let it go free.
  3. Don’t bother trying to get your CSS to validate, except to look for syntax issues. You’re only going to hurt user experience trying to settle for the lowest common denominator.
  4. Use HTML5, but use it like it’s XHTML5. I know it’s a glimmer in the W3C’s eye right now, but you’ll thank me in 5 years.
  5. Polyfills are your friend. CSS PIE will help you achieve enlightenment, even though it has its dark side.
  6. CSS and Javascript do not belong in your HTML. Ever.
  7. jQuery, jQuery UI, and jQuery Mobile. Through this holy trinity, you can accomplish all things.
  8. Wireframe if you feel it is necessary for your clients. Mockup and slice with Photoshop. Don’t start any HTML/CSS without a full mockup.
  9. Don’t over-engineer. There’s no point in going nuts in Javascript for Aunt Edna’s Doll Furniture Emporium.
  10. Load as few external files as possible. Don’t have an external print stylesheet, 50 icon files when you could have used a spritesheet, or a dozen jQuery plugin files that never get touched, that could just be merged together.
  11. Don’t be a slave to backend devs. Pick a language, and learn it. It’s not as hard as you think.
  12. The best solution is almost always a custom one. It will save massive headaches in the long run.
  13. Don’t get caught up in design fads. The homemade look will one day be just as tiresome as the glossy “web 2.0” trend from 2006.
  14. Experiment with new stuff, and don’t be afraid to use Flash if absolutely necessary, but always have a fallback plan.
  15. Make your layouts responsive, but remember this is not always the answer to all mobile user experience problems. Sometimes jQuery mobile, etc. will solve this.
  16. Always plan for IE7 and IE8. Use IETester. IE6 is burning in hell, so no worries there.
  17. Be smart with your SEO. Don’t overdo your SEO, or you will find your SEO fighting an uphill battle it will never win. But if you have a serious budget for SEO, then by all means. SEO.
  18. Don’t settle being employed by ad agencies and web marketing companies for years on end. They help build your portfolio, but are career dead-ends. Keep pushing yourself further.
  19. The quality of your database is directly proportional to the quality of your backend. If you find yourself doing stupid queries, you probably have a stupid schema.
  20. Know a little of everything, find what you like best, then specialize.

And I guess 20 is enough. This philosophy evolved over 7 years of doing this professionally, and has served me pretty well. Hope someone out there finds this useful. And remember, it’s not just common sense… it’s the patented Bartek Web Design Philosophy®.

Javascript CDNs: A Ticking Timebomb

Sorry for the mainstream media headline, but the truth hurts. Javascript CDNs are dangerous and want to harm your grandparents, your kids, and your little dog too. What do I mean by this? Well, let’s look at the advantages and disadvantages:

Advantages:

  1. Potential to sometimes make your website load slightly faster

Disadvantages:

  1. Potential to make your website take longer to load
  2. Potential to prevent your website from loading
  3. Complete reliance on external servers (single point of failure)
  4. Many popular CDNs do not use optimal cache control settings
  5. SSL introduces ethical issues

So let’s look at the first one. the CDN can make your script load faster. It can make it run slower. Consider the odds of the user already having the script. What do you think the chances are of that user having already specifically downloaded, for instance, jquery.min.js v1.7.2? It’s probably safe to assume less than 50% for the average user, right? So then we should all use jquery.latest right? Ha, no. NEVER trust the latest version of jQuery; I speak from firsthand experience. Also consider, if the user does NOT have that version of jQuery, it will have to connect to an external server, and thus will take longer to download than if it were local.

Second, the potential to break your website if the CDN doesn’t connect, or gets hacked. Don’t say “that’s Google’s server, it’ll never happen!” It can, and it does. It’s not a question of if it will happen, but when. And when it happens, a lot of websites are gonna go down for putting too much trust in the cloud. On top of that, some places have a ban on Google domains (such as some schools, workplaces, and entire countries). I’ve seen this happen in the past, and had to stop using CDNs in K-12 educational projects.

Third, reliance on external servers. You are introducing a single point of failure by using a CDN-hosted script. Luckily, there is a way around this; have a local fallback in place. However, this can introduce problems when trying to test your website locally.

Fourth, CDNs don’t generally cache like you think they would. You’d think they’d cache a solid version of jQuery for a week or month, since it’s highly unlikely it’ll change. As far as I can tell, they only cache for days or hours. Does this not defeat the purpose of a Javascript CDN? I think it does.

And finally, SSL. When someone connects to your website via SSL, they are entrusting you not to communicate their requests with remote servers. You are essentially breaking their trust by using a CDN. It may not be a big deal to me and you, but to some users it is.

I have to admit, I’ve been using Javascript CDNs blindly for years now, and only recently did I begin to question whether the effort was worth it. When you do the math, honestly it doesn’t look like it is. Are we really willing to put our eggs in other baskets to save 15kb? Does the potential savings in loading time have enough of an impact to positively affect the user? Are the odds in the user’s favor at all? Ask yourself these questions, and you might be surprised you’ve been living in the cloud computing matrix, and this stuff about CDNs making things faster is irresponsible marketing at best, dangerous at worst. Am I onto something, or am I just being an idiot?