kaoscify
kaoscify

Reputation: 1763

Executing external JS using innerHTML and appendChild

I've been playing around with the Material Design Lite library that Google just launched a few days ago, but have some questions, specifically on how to initiate (or execute?) external JS when the HTML changes using innerHTML and appendChild.

See the first example here. As you can see, the HTML for the menu is already within the HTML file when it is first loaded so the menu works fine.

But in this example, the HTML of the document is modified using JS. However, the menu does not work anymore because the script is not executing, I think.

How can I resolve this issue? What's a better way to achieve this result? I'm a newbie when it comes to JavaScript.

Upvotes: 1

Views: 173

Answers (2)

leo.fcx
leo.fcx

Reputation: 6467

You will need to attach the proper event listener from the library. With this change (adding componentHandler.upgradeAllRegistered(); after appending the item) it should work:

document.body.appendChild(menu);
componentHandler.upgradeAllRegistered();

Upvotes: 2

TW80000
TW80000

Reputation: 1515

When the menu button is inserted dynamically (when the user clicks), it doesn't get assigned the event listeners to show the menu. I'm guessing that the material design library parses the HTML when it (the library) gets loaded (since you're loading it at the bottom of your HTML document). Since it's already loaded by the time the user clicks, it doesn't check the new element that has been inserted and can't assign it the event listeners.

If this is the case, you'll need to find a way to get the library to recognize your new button.

Upvotes: 0

Related Questions