Skip to content

Instantly share code, notes, and snippets.

@landsman
Last active February 24, 2018 19:28
Show Gist options
  • Select an option

  • Save landsman/4469bdd49120ea2b50df9a995aa1225d to your computer and use it in GitHub Desktop.

Select an option

Save landsman/4469bdd49120ea2b50df9a995aa1225d to your computer and use it in GitHub Desktop.
class Sidebar {
constructor(c)
{
this.burger = document.getElementById(c.burger_id);
this.sidebar = document.getElementById(c.sidebar_id);
this.close = document.getElementById(c.close_id);
this.sidebar_open = c.sidebar_open_class;
this.body_sidebar_open = c.body_sidebar_open;
this.is_open = false;
this.initEvents();
}
openIt()
{
if(this.is_open){
return;
}
this.is_open = true;
this.doOffset();
this.sidebar.classList.add(this.sidebar_open);
document.body.classList.add(this.body_sidebar_open);
}
closeIt()
{
if(false === this.is_open) {
return;
}
this.is_open = false;
this.sidebar.classList.remove(this.sidebar_open);
document.body.classList.remove(this.body_sidebar_open);
}
doOffset()
{
let bodyPadding = document.body.style.paddingTop;
if(bodyPadding) {
this.sidebar.style.paddingTop = bodyPadding;
}
}
/**
* If you click outside sidebar content (overlay), close sidebar
* Todo: test it for performance (ever click calling this method)
* @param event
*/
checkClickOutside(event)
{
console.log('event', event);
console.log('content', this.sidebar.firstChild);
console.log('targer', event.target);
if(event.target === this.sidebar && this.is_open)
{
this.closeIt();
}
}
/**
* call by ESC key
* @param event
*/
escape(event)
{
console.log(event);
event = event || window.event;
if(this.is_open && event.keyCode === 27)
{
this.closeIt();
}
}
initEvents()
{
/**
* open sidebar
*/
this.burger.addEventListener('click', this.openIt.bind(this));
/**
* close sidebar by icon
*/
this.close.addEventListener('click', this.closeIt.bind(this));
/**
* click to overlay for close sidebar
*/
this.sidebar.addEventListener('click', this.checkClickOutside.bind(this));
/**
* close sidebar by ESC key
* @param evt
*/
document.addEventListener('keydown', this.escape.bind(this));
}
}
export default Sidebar;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment