Last active
January 26, 2016 21:37
-
-
Save joshdcomp/04611ba4d344a99b8d02 to your computer and use it in GitHub Desktop.
When writing event handlers, manipulate elements relative to the element was clicked to avoid unintended consequences.
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
/** | |
* The way this is written there are 2 major assumptions: | |
* | |
* 1) There will only ever be one `.email_subscribe` on the page (and if there’s more, | |
* they’re all going to open/close at the same time) | |
* 2) These elements will exist on document load…so if these things get built by js or are | |
* loaded after docload, these click events won’t do anything | |
*/ | |
$('.subscribe-close').on('click', function(){ | |
$('.email_subscribe').removeClass('email_subscribe--opened'); | |
}); | |
/** | |
* We can assume 2) will be true most of the time so that's fine, but 1) is a risky assumption | |
* that you don't need to make…and if you do can come back to bite you in the butt, especially | |
* given how easy the fix is: | |
*/ | |
$('.subscribe-close').on('click', function(e){ | |
// Use closest in favor of parents because it's way faster, and parents returns every single | |
// match, not just the first one: http://stackoverflow.com/questions/10499435/parent-vs-closest | |
var $wrapper = $(e.currentTarget).closest('.email_subscribe'); | |
// You could also do $(this), but I prefer to do e.currentTarget because you can't always | |
// assume the context of the handler function is | |
// -- | |
$wrapper.removeClass('email_subscribe--opened'); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment