Last active
December 30, 2015 06:59
-
-
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/
This file contains hidden or 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
$(".sandwich").click(function(e) { | |
$(e.currentTarget).toggleClass("active"); | |
}); |
This file contains hidden or 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
// 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