Skip to content

Instantly share code, notes, and snippets.

@MoOx
Last active December 12, 2015 09:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MoOx/4753179 to your computer and use it in GitHub Desktop.
Save MoOx/4753179 to your computer and use it in GitHub Desktop.
Please show me how will you write that without jQuery please :) (It's not I'm not able to do it, but you already know that right ?)
// togglable ability (used for navbar)
$('.js-togglable').each(function() {
var togglableContainer = this;
$('.js-togglable__toggler', togglableContainer).on('click keyup', function() {
$('.js-togglable__item', togglableContainer).toggleClass('js-togglable__item--hide');
});
});
@anthonyshort
Copy link

Something like this might work:

document.querySelectorAll('.js-togglable').forEach(function(el){
  var item = el.querySelector('.js-togglable__item');
  var toggler = el.querySelector('.js-togglable__toggler');

  var toggle = function(event){
    item.classList.toggle('js-togglable__item--hide');
  };

  toggler.addEventListener('click', toggle);
  toggler.addEventListener('keyup', toggle);
});

@anthonyshort
Copy link

Couple more lines than the jQuery. Could be written a little smaller probably. That should work but I haven't tested it with anything. Still beats adding a giant library.

Obviously with more complex stuff you'll abstract some code out or need to use something like jQuery but the majority of sites could easily go without needing it these days.

@MoOx
Copy link
Author

MoOx commented Feb 11, 2013

So I just need to add
NodeList.prototype.forEach = Array.prototype.forEach; to make this work like a charm. Bye jQuery :)
Thanks @anthonyshort !
Now I just need a nice way to includes polyfills to support old browsers :)

@MoOx
Copy link
Author

MoOx commented Feb 11, 2013

I found an other way for the forEach trick.

Array.prototype.slice.call(document.querySelectorAll('.js-togglable')).forEach(function(el){
    var toggler = el.querySelector('.js-togglable__toggler');
    var items = Array.prototype.slice.call(el.querySelectorAll('.js-togglable__item'));

    var toggle = function(event) {
        items.forEach(function(item) {
            item.classList.toggle('js-togglable__item--hide');
        });
    };

    toggler.addEventListener('click', toggle);
    toggler.addEventListener('keyup', toggle);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment