Skip to content

Instantly share code, notes, and snippets.

@Krxtopher
Last active December 30, 2015 06:59
Show Gist options
  • Save Krxtopher/7793289 to your computer and use it in GitHub Desktop.
Save Krxtopher/7793289 to your computer and use it in GitHub Desktop.
JQuery sample implementation of example scenario in this article: http://gomakethings.com/ditching-jquery-for-vanilla-js/
$(".sandwich").click(function(e) {
$(e.currentTarget).toggleClass("active");
});
// Class Handlers
var hasClass = function (elem, className) {
return new RegExp(' ' + className + ' ').test(' ' + elem.className + ' ');
}
var addClass = function (elem, className) {
if (!hasClass(elem, className)) {
elem.className += ' ' + className;
}
}
var removeClass = function (elem, className) {
var newClass = ' ' + elem.className.replace( /[\t\r\n]/g, ' ') + ' ';
if (hasClass(elem, className)) {
while (newClass.indexOf(' ' + className + ' ') >= 0 ) {
newClass = newClass.replace(' ' + className + ' ', ' ');
}
elem.className = newClass.replace(/^\s+|\s+$/g, '');
}
}
// Sandwich Functions
if ( 'querySelector' in document && 'addEventListener' in window ) {
var sandwiches = document.querySelectorAll('.sandwich');
[].forEach.call(sandwiches, function (sandwich) {
sandwich.addEventListener('click', function(e) {
if ( hasClass(sandwich, 'active') ) {
removeClass(sandwich, 'active');
}
else {
addClass(sandwich, 'active');
}
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment