This is a quick #knowledge drop.

Today, a co-worker pointed out a neat little touch on the website for Slim Framework. When you open a new tab or otherwise lose focus on the browser, the title of the website changes to

♬ Baby come back! Any kind of fool could see… ♬

Which is hilarious, plus it’s a decent song.

I said to myself “Self, you need to do this on leihu.com, cause, you know, eggs.”

After work, I tried to figure this out. Unfortunately, like the good developers they are, everyone on the web is minifying their code. The only StackExchanges I could find only offered a basic gist of an idea.

The first problem, is that Slim Framework is a single page site, so they can get away with hardcoding the default title, something leihu.com cannot.

Another problem is that .on(‘focus’,function(){...}); wants to fire every time the page loads, ‘cause focus. That just wouldn’t work, as everyone knows the best eggs are of the easter variety, and I can’t have my stupid site giving this one away on first visit, it’s much better as a surprise.

About forty-four minutes of guessing, and trying to read minified code, I eureka’d. Below I’ve offered up the code needed to accomplish this rad task, just open a new tab then come back for a full demo. I commented the code for further explanation, but don’t hesitate to send .(JavaScript must be enabled to view this email address) my way.

// =========
// title egg
// =========

	// set the base title
	var baseTitle = window.document.title;

	// listen for focus on window
	$(window).on('focus',function(){
		// check the title, if it's not equal to baseTitle
		if(document.title != baseTitle){
			// then change it to...
			document.title = '...and I say hello ♬';
			// 1 second later, change it to baseTitle
			setTimeout(function(){
				document.title = baseTitle;
			}, 1000);
		}
		// otherwise just load the baseTitle
		else{ document.title = baseTitle; }
	});

	// listen for loss of focus on window
	// focusing the address bar will also trigger this
	$(window).on('blur',function(){
		// change the title to...
		document.title = '♫ You say goodbye...';
	});
javascript
dismiss