0

I'm using a for loop to dynamically name and fill buttons (with text and with code). One thing I had a problem with was dynamically allocating onclick functionality to the buttons, but I seemed to have fixed it with:

document.getElementById(ID_HERE).onclick = FUNCTION();

The problem is when I add this code, the buttons trigger themselves on the load of the webpage instead of the click.

I put the full code below for both the HTML and the Javascript.

JavaScript:

var routes = "";
var elem = "";
var locationid = "50017"
var currentRoute = "the Londinium Way"
function possibleRoutes(){
    document.write("<div id='container'>");
    document.write("<center><b> Welcome to ");
    document.write(currentRoute);
    document.write("!<br>")
    document.write("Your options are:");
    for (i = 0; i<routes.length;i++){
        var options = routes[i];
        var temp = "button" + i
        document.write("<button id='button'></button>");
        document.getElementById('button').id = temp;
        document.getElementById(temp).innerHTML=routes[i][0];
        document.getElementById(temp).onclick = getRoutes(routes[i][1]);
        console.log(routes[i]);
        console.log(routes[i][1]);
    }
    document.write("<br><img src='http://192.168.1.151:8000/map.jpg'>");
    document.write("</b></center></div>");
}
function getRoutes(locationid) {
  var routesURL = 'http://cors.io/?u=http://orbis.stanford.edu/api/sites/' + locationid;
  $.ajax({
    type: 'GET',
    url: routesURL
  }).done(function(data) {
    console.dir(data);
    dataParsed = JSON.parse(data);
    currentRoute = dataParsed.prefname;
    routes = dataParsed.routes;
    console.log(routes);
    clearScreen();
  });
}
function clearScreen(){
    if (document.contains(document.getElementById("container"))){
            elem = document.getElementById("container");
            elem.remove();
    }
    possibleRoutes();
}

HTML:

<html>
    <head>

        <title> Londinium Trail </title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
        <script src="http://192.168.1.151:8000/scripts/game.js"> </script>
    </head>
    <body>
        <script>
        getRoutes(50017);
        </script>
    </body>
</html>
wpercy
  • 9,636
  • 4
  • 33
  • 45
Josh
  • 29
  • 4

2 Answers2

3

JAVASCRIPT

Try to use addEventListener instead :

document.getElementById(ID_HERE).addEventListener("click", myFunction);

JQUERY

If you're using jquery :

$('body').on('click', '#ID_HERE', myFunction);

Take a look at addEventListener vs onclick.

Hope this helps.

Community
  • 1
  • 1
Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
2

The issue is that you are calling the function by using FUNCTION();

Since your code appears to be using JQuery, consider using the .on method to attach a click listening:

$(document).on('click', '#ID_HERE', function(){
  function_to_run();
});
Phil
  • 2,797
  • 1
  • 24
  • 30