Last active
October 26, 2018 11:54
-
-
Save marcelmokos/ab4352f45b6ee9e73d25f3425b16b113 to your computer and use it in GitHub Desktop.
Example code style with comments (comments are meant to explain code style do not use comments like this in application)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function initToggle({ | |
TOGGLE_SELECTOR = ".js-toggle", | |
TOGGLE_FOCUSED_CLASS = "toggle--focused", | |
TOGGLE_ITEM_OPEN_CLASS = "toggle__item--open", // use constants for class names and selectors variable name should end with _CLASS or _SELECTOR | |
}) { // use init functions that encapsulate functionality | |
const $toggle = $(TOGGLE_SELECTOR); // jQuery objects variable names should start with $ for jQuery elements | |
$toggle.on("focus", (event) => { | |
const $this = $(event.currentTarget); | |
$this.addClass(TOGGLE_FOCUSED_CLASS); | |
}); | |
$toggle.on("focusout",(event) => { | |
const $this = $(event.currentTarget); | |
$this.addClass(TOGGLE_FOCUSED_CLASS); | |
}); | |
function toggleItemOpen($toggleElement) { // create functions for code used multiple times and name them properly | |
const toggleItemSelector = $toggleElement.data("toggleItem"); // variables holding selectors should end with _Selector | |
const $toggleItem = $toggleElement.find(toggleItemSelector); // use cashed selectors if possible | |
if ($toggleItem.hasClass(TOGGLE_ITEM_OPEN_CLASS)) { | |
$toggleElement.setAttribute("aria-expanded", false); | |
$toggleItem | |
.removeClass(TOGGLE_ITEM_OPEN_CLASS) | |
.slideUp(); | |
return; // better to use early return over else block | |
} | |
$toggleElement.setAttribute("aria-expanded", true); | |
$toggleItem | |
.addClass(TOGGLE_ITEM_OPEN_CLASS); | |
.slideDown(); | |
} | |
$toggle.click((event) => { | |
$toggleElement = $(event.currentTarget); // use named this | |
toggleItemOpen($toggleElement); | |
}); | |
const ENTER_KEY = 13; // name unclear constants | |
$toggle.keypress((event) => { // elements with onClick have to have key press as well | |
$toggleElement = $(event.currentTarget); // use named this | |
switch (event.which) { | |
case ENTER_KEY: | |
toggleItemOpen($toggleElement); | |
} | |
}); | |
} | |
$(document).ready(() => { // keep the document ready simple as possible | |
initToggle(); // only init functions in document ready | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment