Based on GitHub discourse, I have a couple of working solutions to the (hopefully soon to be resolved) issue of having a MDL drawer close when link is clicked. At the moment I'm using:
function close() {
var d = document.querySelector('.mdl-layout');
d.MaterialLayout.toggleDrawer();
}
document.querySelector('.mdl-layout__drawer').addEventListener('click', close);
Other variations are:
1.
document.querySelector('.mdl-layout__drawer').addEventListener('click', function () {
document.querySelector('.mdl-layout__obfuscator').classList.remove('is-visible');
this.classList.remove('is-visible');
}, false);
2.
function close() {
var d = document.querySelector('.mdl-layout');
d.MaterialLayout.toggleDrawer();
}
var drawer_container = document.getElementsByClassName('mdl-layout')[0];
drawer_container.querySelector('.mdl-layout__drawer').addEventListener('click', 'close');
Someone in the discussion mentioned the idea of targeting the querySelector
so as not to require looking through the entire document and I came up with the following two variations:
3.
var drawer_container = document.getElementsByClassName('mdl-layout')[0];
# no IDs in the html code.
drawer_container.querySelector('.mdl-layout__drawer').addEventListener('click', function () {
var obfuscator = document.querySelector('.mdl-layout__obfuscator');
if (obfuscator.classList.contains('is-visible')) {
obfuscator.classList.remove('is-visible');
this.classList.remove('is-visible');
}
}, false);
4.
function close() {
var d = document.getElementsByClassName('mdl-layout__container')[0].querySelector('.mdl-layout');
d.MaterialLayout.toggleDrawer();
}
var drawer_container = document.getElementsByClassName('mdl-layout')[0];
drawer_container.querySelector('.mdl-layout__drawer').addEventListener('click', 'close');
In both of my versions the browser has to run document.getElementsByClassName
as well as a targeted querySelector
call.
In my first version there is also the check: classList.contains('is-visible')
which someone had recommended, but which seems unnecessary as, the function is being called from an item that is only visible if classList.contains('is-visible')
is true.
I added the following calls to each of my variations (#3 and 4), within the functions:
console.time("anonymous");
console.timeEnd("anonymous");
console.time("close function");
console.timeEnd("close function");
And the one with the if
statement runs in .39ms
. Without the if
statement they both run in .19ms
. But I'm also not measuring the getElementsByClassName
and querySelector
methods that, if I understand correctly, are running on page load.
When I ran console.time("first");
and console.timeEnd("first");
through the first, and to me, prettiest code, the time was 23ms
.
Apparently ie8, which I want to support, doesn't support getElementsByClassName.
I'm hoping someone can provide and explain an optimal solution to this relatively simple problem.
Here's a CodePen (not mine).