0

I want to open a MDCMenu with a button from the MDCTopAppBar. The documentation lacks sample code how to do this. So I'm trying to do this via EventListener. Please let me know if there are smoother ways to do so.

The EvenListener complains MDCMenu was not defined.

import {MDCMenu} from '@material/menu';
import {MDCTopAppBar} from '@material/top-app-bar';
import {MDCMenuSurface} from '@material/menu-surface';

const topAppBarElement = document.querySelector('.mdc-top-app-bar');
const topAppBar = new MDCTopAppBar(topAppBarElement);

console.log('hello world');

const menu = new MDCMenu(document.querySelector('.mdc-menu'));

document.querySelector('#menu-button').addEventListener("click", () => {
   menu.open != menu.open;
});

menu is defined as global constant here. How can it be that it is unknown to the console or this EventListener?

Clicking the button triggers the following in the console:

ReferenceError: MDCMenu is not defined localhost:8080:1:14
    onclick http://localhost:8080/:1

Something seems to be wrong with the import. But the EvenListener just refers to the instance, not the class. I don't understand why it would even need the MDCMenu...

MPW
  • 161
  • 1
  • 3
  • 16

2 Answers2

1

In vanilla JS you have to address the fully qualified name.

const menu = new mdc.menu.MDCMenu(document.querySelector('.mdc-menu'));

See Fiddle

p.s.: i think the event listener should do menu.open = !menu.open;

Imperative
  • 3,138
  • 2
  • 25
  • 40
  • The import makes MDCMenu available, without full qualified name. – MPW Dec 11 '19 at 16:42
  • And thanks for the hin with menu.open = !menu.open. :) That change was necessary aswell, of course. – MPW Dec 11 '19 at 16:43
0

I had forgotton to import MDCMenuSurface. The full, running code is:

import {MDCMenu} from '@material/menu';
import {MDCTopAppBar} from '@material/top-app-bar';
import {MDCMenuSurface} from '@material/menu-surface';

// Instantiation
const topAppBarElement = document.querySelector('.mdc-top-app-bar');
const topAppBar = new MDCTopAppBar(topAppBarElement);

const menu = new MDCMenu(document.querySelector('.mdc-menu'));

function openMenu() {
   menu.open = !menu.open;

}

document.querySelector('#menu-button').addEventListener("click", openMenu);
MPW
  • 161
  • 1
  • 3
  • 16