A few years back I can remember visiting
Sitepoint and reading an article about...something. What I distinctly remember is that I was able to hide the sidebar so that I wouldn't be distracted by other page elements floating next to the content I was trying to focus on.
After discovering how cool that actually was, I quickly began trying to dig up how it was done but to my surprise - I came up empty handed when looking through their source.
Well, years later, my code hunting techniques have vastly improved...not to mention my code writing ;) With that said, here is a quick copy & paste job for you to play with (directly from this site)
For a quick demo of this code snippet, simply click the left icon directly above the sidebar of this page.
toggle sidebar (JavaScript)
/* used in conjuction with both the dollar $() function and addEvent */
// addEvent() found @ http://www.dustindiaz.com/rock-solid-addevent/
// $() found @ http://www.dustindiaz.com/top-ten-javascript
var togBar = {
bar : null,
nest : null,
init : function() {
this.bar = $('sideBar');
this.nest = document.createElement('div');
this.nest.id = 'toggler';
this.run();
},
run : function() {
$('body').appendChild(this.nest);
this.nest.innerHTML = '<a id="open" title="Open Sidebar">Show Sidebar</a>';
this.nest.innerHTML += '<a id="closed" title="Hide Sidebar">Hide Sidebar</a>';
this.togglers();
},
togglers : function() {
addEvent($('open'),'click',this.opener);
addEvent($('closed'),'click',this.closer);
},
opener : function() {
togBar.bar.className = 'opened';
},
closer : function() {
togBar.bar.className = 'closed';
}
};
function commonListeners() {
togBar.init();
}
addEvent(window,'load',commonListeners);
CSS for Toggling
div#sideBar.opened { display:block; }
div#sideBar.closed { display:none; }
What it's doing
First you'll notice that we're appending the
open and
close links to the document with JavaScript. This is mainly so that we don't have these links just lying around on our document that when you click them - do nothing. In other words, if they make it to the page, the user most likely has JavaScript enabled.
Next you can see in the CSS we have defined two classes. 'opened' simply has
display:block; and 'closed' is
display:none; appropriately.
Finally, we assign an event to each link that runs the togBar.opener method, and the togBar.closer method which simply swap out the className's.
That's it! Easy sideBar toggling with unobtrusive JavaScript
Todays question and book information
The winner of today’s contest will receive a copy of
Web Standards Solutions by
Dan Cederholm.
Give me a match on Google Fights that will make me laugh.