Skip to content

Instantly share code, notes, and snippets.

@AndreKelling
Last active April 25, 2018 19:24
Show Gist options
  • Save AndreKelling/e00fdd25e3352f853182cbf87e1e5e3e to your computer and use it in GitHub Desktop.
Save AndreKelling/e00fdd25e3352f853182cbf87e1e5e3e to your computer and use it in GitHub Desktop.
toggle button jquery + js module
// jquery
var allToggleContents = $('.toggle_content').hide();
$('.toggle_handler').click(function() {
toggleControl($(this));
});
function toggleControl(button) {
var container = $("#"+button.attr('aria-controls'));
//console.log(container);
if ( container.attr('aria-expanded')=='true' ) {
button.attr( 'aria-expanded', 'false' );
container.attr( 'aria-expanded', 'false' );
container.slideUp();
} else {
button.attr( 'aria-expanded', 'true' );
container.attr( 'aria-expanded', 'true' );
container.slideDown();
}
return false;
}
// js - module pattern - self starting
var Toggler = (function() {
var plugin = {};
plugin.init = function() {
document.querySelectorAll('[data-toggler]').forEach(function (el) {
//console.log(el.dataset.toggler);
plugin[el.dataset.toggler](el);
})
};
plugin.toggle = function(button) {
button.addEventListener('click', function(){
// control by ID of target element
let container = document.getElementById(button.getAttribute('aria-controls'));
//console.log(container);
if (container.getAttribute('aria-expanded') === 'true') {
button.setAttribute( 'aria-expanded', 'false' );
container.setAttribute( 'aria-expanded', 'false' );
} else {
button.setAttribute( 'aria-expanded', 'true' );
container.setAttribute( 'aria-expanded', 'true' );
}
});
};
return {
init: plugin.init
};
}());
Toggler.init();
// es6
const Toggler = () => {
const toggle = (button) => {
button.addEventListener('click', function(){
// control by ID of target element
let container = document.getElementById(button.getAttribute('aria-controls'));
if (container.getAttribute('aria-expanded') === 'true') {
button.setAttribute( 'aria-expanded', 'false' );
container.setAttribute( 'aria-expanded', 'false' );
} else {
button.setAttribute( 'aria-expanded', 'true' );
container.setAttribute( 'aria-expanded', 'true' );
}
});
};
document.querySelectorAll('[data-toggler]').forEach((el) => {
toggle(el);
});
};
Toggler();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment