Search code examples
javascriptwindows-8dom-eventsmicrosoft-metro

Can't add an event to a button


I am working on this Windows 8 test application and I'm using the grid app template. In the itemDetail.html I have the following HTML code (I removed all the other code in that div and added this button, the rest of the html is untouched):

<div class="item-info">
     <button id="menuLink">Get me the menu</button>
</div>

I added the following JS code in the ready member of the Pages.define function in itemDetail.js:

var menuButton = document.getElementById("menuLink");
menuButton.setAttribute("onclick", "menuButtonClickHandler()");

The menuButtonClickHandler() function is declared right after the Pages.define function with the following code:

function menuButtonClickHandler() {
    var messageDialog = new Windows.UI.Popups.MessageDialog("Here's your menu");
    }

When I click the button I get the following exception:

0x800a1391 - JavaScript runtime error: 'menuButtonClickHandler' is undefined

Where am I suppose to 'define' this function? the template is using every other code from the JS file where that function already is so the function should be available to it.

Also for some strange reason I can't even add the event if I use addEventListener:

menuButton.addEventListener("click", buttonClickHandler, false);

Solution

  • The way you try to add event listener is quite dirty and not working obviously. Try something like this:

    var menuButton = document.getElementById("menuLink");
    menuButton.addEventListener("click", function(){
         //do something
    }, false);