Search code examples
javascripthtmlcrosswalk

onclick attribute not working even after the function is defined


I'm dynamically populating html by using a for loop like this

function htmlpopulate() {
  /*some DOM manipulations*/
  setInterval(loadhtml, 5000); //getting live data
}

function loadhtml {
  activediv.innerHTML = '';
  for (i = 0; i < userarray.length; i++) {
    var temp = userarray[i].trim();
    activediv.innerHTML += '<p onclick="makecall(' + "'" + temp + "'" + ');return false;")">' + temp + '</p><br/>';
  }
}

function makecall(data) {
  console.log(data);
}

output:makecall is not defined
how to make the inline function to call that defined function?


Solution

  • function makecall must be defined in the global context:

    window.makecall = function (data) {
      console.log(data);
    };
    

    Also, you need to sort out quotes and parenthesis in

    activediv.innerHTML += '<p onclick="makecall(' + "'" + temp + "'" + 
      ');return false;")">' + temp + '</p><br/>';
    

    you don't need )" after return false;".