0

I'm trying to make message appear on button click in Cordova. I'm gettings this error:

Uncaught TypeError: Cannot read property 'addEventListener' of index.js:6
null
    at Object.initialize (index.js:6)
    at index.js:39

Error message points to this line:

btn.addEventListener('click', this.buttonController, false);

I have this code in js file:

var app = {

    initialize: function() {
    var btn = document.getElementById("btn1");
    btn.addEventListener('click', this.buttonController, false);
    },

    onDeviceReady: function() {
    },

    buttonController: function () {
    navigator.notification.alert(
        'Button Pressed!',  // message
        alertDismissed,         // callback
        'Title',            // title
        'Button Name'                  // buttonName
    );
    alert("clicked");
    }
};

app.initialize();
Andy D
  • 125
  • 11
  • The error tells you that ```btn``` is ```null``` which means that ```document.getElementById``` failed to find any element with the id ```btn``` – Stefan Octavian Apr 04 '18 at 17:59
  • Is there an Element with the ID `btn1` when this part of the script runs? – Luca Kiebel Apr 04 '18 at 17:59
  • Thanks people, I already figured this out: buttons came later that script tag in html, I had to add defer in script tag. Thjs helped me:https://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element – Andy D Apr 05 '18 at 01:31

0 Answers0