I'm no stranger to JS, but I think I still have a lot to learn. I originally wrote this code to manipulate a "help" bar, which would be positioned as a thin ribbon on the side of the browser window, which when hovering over or clicking would open up and display it's contents. Nothing major, but an okay example to use here.
$(document).ready(function () {
var open = false;
var peek = false;
var helpBar = $(".help-bar");
var helpIcon = $(".help-icon");
var help = helpBar.add(helpIcon); // Put both together to do the same things
helpBar.click(function () {
toggleHelp();
});
helpBar.hover(function () {
togglePeek();
});
function toggleHelp() {
if (open) {
changeRightValue(help, "0", "slow");
toggleArrow("Open");
open = false;
}
else {
changeRightValue(help, "280", "fast");
toggleArrow("Close");
open = true;
}
}
function togglePeek() {
if (open == false) {
help.stop();
if (peek) {
changeRightValue(help, "0", "fast");
peek = false;
}
else {
changeRightValue(help, "5", "fast");
peek = true;
}
}
}
function changeRightValue(element, amount, speed) {
element.animate({ right: amount }, speed);
}
function toggleArrow(direction) {
helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
}
});
It works fine, but then I wondered whether grouping related items into objects might help a little:
$(document).ready(function(){
var open = false;
var peek = false;
var helpBar = $(".help-bar");
var helpIcon = $(".help-icon");
var helpSection = helpBar.add(helpIcon); // Put both together to do the same things
var help = {};
var utils = {};
help.toggle = function(){
if (open) {
utils.changeRightValue(helpSection, "0", "slow");
utils.toggleArrow("Open");
open = false;
}
else {
utils.changeRightValue(helpSection, "280", "fast");
utils.toggleArrow("Close");
open = true;
}
};
help.peek = function(){
if (open == false) {
helpSection.stop();
if (peek) {
utils.changeRightValue(helpSection, "0", "fast");
peek = false;
}
else {
utils.changeRightValue(helpSection, "5", "fast");
peek = true;
}
}
};
utils.changeRightValue = function(element, amount, speed){
element.animate({right:amount}, speed);
};
utils.toggleArrow = function(direction){
helpIcon.css("background", "url('/images/buttons/zapp/arrow" + direction + ".png') no-repeat 0px 50%");
};
// jQuery DOM
helpBar.click(function () {
help.toggle();
};
helpBar.hover(function () {
help.peek();
};
});
Is this that much of an improvement over the first? Is there another way that I should be writing this kind of code?