In recent years, jQuery has become the de-facto JavaScript library on the web.
It irons out many cross-browser inconsistencies and adds a welcome layer of syntactic sugar to client-side scripting.
Yet, all too often we see jQuery being used to do something that vanilla JavaScript could do just as well, if not better.
That’s why we’ve decided to set you a little challenge: convert our jQuery into plain old JavaScript.
Successful entries will be those who get things working in any browser without a single jQueryism.
Those looking to score extra points can do so by making their JavaScript backwards compatible, so that it doesn’t break in older browsers.
The jQuery we want you to convert powers a simple tab-based navigation. The content of the tabs resides in different files which are loaded into the main page using AJAX.
You can see the code involved below, or download the files from here.
You can see the tab-based navigation in action here.
Entries need only include the JavaScript, but please use spoiler tags to hide the answers that you post.
For example, this:
[noparse]
[spoiler]Like this[/spoiler]
[/noparse]
Renders this:
[spoiler]Like this[/spoiler]
To help you get started with the challenge, you’ll find a zip file attached to the end of this post that contains the following code.
Please note: this won’t work locally in Chrome (owing to the local AJAX requests). To get around this, please either use a different browser, a local server stack (such as xampp or [URL=“http://www.easyphp.org/”]easyphp), or a remote server.
Good Luck!
index.html
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Tabbed panels</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<h1>JS Tabs Challenge</h1>
<p>All too often jQuery is used to do something that vanilla JavaScript can do just as well, if not better.<p>
<p>Your challenge is to convert our jQuery into plain old JavaScript.</p>
<div class="tabs">
<ul class="nav">
<li><a href="tab1.html">Tab 1</a></li>
<li><a href="tab2.html">Tab 2</a></li>
<li><a href="tab3.html">Tab 3</a></li>
</ul>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="js/tabs.js"></script>
</body>
</html>
tab1.html
<h2>Here is the heading for Tab#1</h2>
<p>Liquor ipsum dolor sit amet glenburgie pappy van winkle. Amaretto sour absolut clynelish macuá stinger singapore sling tanqueray vodka sundowner, ardmore wild turkey; colombia? Cactus jack alexander gin fizz kahlua royal bermuda cocktail the last word ballantine dalwhinnie aultmore smirnoff grand marnier! </p>
<p>Fish house punch brandy daisy brass monkey moonwalk. Murphy's corn n' oil dufftown agent orange kensington court special drumguish kamikaze; chopin french 75. Dufftown my fair lady. Jacquin imperial moscow mule. Van winkle family reserve sazerac; sundowner; sake manhattan jack rose kamikaze loch lomond. Remy martin lemon split mai-tai bowmore polmos krakow colorado bulldog.</p>
tab2.html
<h2>Here is the heading for Tab#2</h2>
<p>Negroni glenturret strega el presidente dalmore miltonduff, "tom and jerry." Singapore sling teacher's oban glogg jim beam whiskey sour edradour, glen elgin. Farnell seven and seven tormore, drambuie nikolaschka blue lagoon, ardmore chopin smirnoff charro negro sloe gin balmenach alexander. </p>
<p>Tom and jerry, piscola piña colada blair athol sea breeze kensington court special manhattan metaxa captain morgan. Speyside wolfram springbank greyhound; montgomery lime rickey matador churchill, churchill, ramos gin fizz harvey wallbanger deanston bloody aztec brackla. Polmos krakow kalimotxo, highland park metaxa hurricane paradise loch lomond early times?</p>
tab3.html
<h2>Here is the heading for Tab#3</h2>
<p>Polmos krakow madras dufftown cuba libre white horse, gimlet lejon v.o. tom collins. Ruby dutchess vodka sunrise, gin and tonic lagavulin buck's fizz: four score strathmill metaxas sake bomb tanqueray. Fettercairn salty dog kremlin colonel; spanish coffee, pegu white horse crown royal kahlua, "glen ord gin pahit; van winkle family reserve?" Mai-tai, salty dog. </p>
<p>Cosmopolitan glogg allt-á-bhainne j & b stinger balblair, fish house punch. Drambuie usher's sidecar long island iced tea paradise jameson kirsch creamsicle, brandy sour mudslide gordon's black russian tomintoul vodka sunrise." Jameson coronet vso fleischmann's bearded lady, metaxa, tomatin strathisla fettercairn gilbey's courvoisier.</p>
style.css
/* small reset as needed for this page only*/
html, body{
margin: 0;
padding: 0;
}
h1, h2, p, ul {
margin: 0 0 15px;
padding: 0;
}
ul {
list-style: none;
}
h1, h2 {
font-size: 140%;
}
/* end reset */
body {
padding: 25px;
}
.tabs {
width: 600px;
background: #f8f8f8;
border: 1px solid #cccccc;
}
.nav {
background: #E8E8E8;
border-bottom: 1px solid #cccccc;
float: left;
width: 100%;
}
.nav li {float: left}
.nav a {
float: left;
padding: 8px 15px;
text-decoration: none;
font-weight: bold;
border-right: 1px solid #cccccc;
}
.nav,.nav a,.nav a:visited{
color: #484848;
background: #E8E8E8;
}
.nav a:hover,
.nav a.selected {
background: #f8f8f8;
position: relative;
margin-bottom: -1px;
padding-bottom: 9px;
}
.nav a.selected {
cursor: default;
}
.content {
padding: 10px 25px;
clear: both;
width: 550px; /* ie6/7 haslayout trip */
}
tabs.js
$(document).ready(function () {
$(".tabs .nav a").on("click", function (e) {
e.preventDefault();
var $tab = $(this),
fileToLoad = $tab.attr("href"),
$nav = $tab.parents('.nav'),
$content = $nav.siblings('.content');
// Prevent the same tab from being reloaded
if ($tab.hasClass("selected")) {
return false;
}
// check if section for content should be added
if (!$content.length) {
$content = $('<div>').addClass('content');
$content.insertAfter($tab.parents('.nav'));
}
// change selected tab and load new content
$nav.find('a').removeClass("selected");
$content.fadeOut('slow', function () {
$tab.addClass("selected");
$(this).load(fileToLoad).fadeIn();
});
});
$('.tabs .nav a:first').trigger('click');
});